Skip to content

Commit d610f01

Browse files
authored
Add toString, toDateString and toTimeString to Date (AssemblyScript#1829)
1 parent eb964f0 commit d610f01

File tree

5 files changed

+1493
-328
lines changed

5 files changed

+1493
-328
lines changed

std/assembly/date.ts

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,50 @@ export class Date {
208208
"Z"
209209
);
210210
}
211+
212+
toDateString(): string {
213+
// TODO: use u64 static data instead 4 chars
214+
// also use stream itoa variants.
215+
const weeks: StaticArray<string> = [
216+
"Sun ", "Mon ", "Tue ", "Wed ", "Thu ", "Fri ", "Sat "
217+
];
218+
219+
const months: StaticArray<string> = [
220+
"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ",
221+
"Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "
222+
];
223+
224+
var mo = this.month;
225+
var da = this.day;
226+
var yr = this.year;
227+
var wd = dayOfWeek(yr, mo, da);
228+
var year = abs(yr).toString().padStart(4, "0");
229+
if (yr < 0) year = "-" + year;
230+
231+
return (
232+
unchecked(weeks[wd]) +
233+
unchecked(months[mo - 1]) +
234+
da.toString().padStart(2, "0") +
235+
" " + year
236+
);
237+
}
238+
239+
// Note: it uses UTC time instead local time (without timezone offset)
240+
toTimeString(): string {
241+
// TODO: add timezone
242+
return (
243+
this.getUTCHours().toString().padStart(2, "0") +
244+
":" +
245+
this.getUTCMinutes().toString().padStart(2, "0") +
246+
":" +
247+
this.getUTCSeconds().toString().padStart(2, "0")
248+
);
249+
}
250+
251+
// Note: it uses UTC datetime instead local datetime (without timezone offset)
252+
toString(): string {
253+
return this.toDateString() + " " + this.toTimeString();
254+
}
211255
}
212256

213257
function epochMillis(
@@ -275,7 +319,7 @@ function dayOfWeek(year: i32, month: i32, day: i32): i32 {
275319
const tab = memory.data<u8>([0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]);
276320

277321
year -= i32(month < 3);
278-
year += year / 4 - year / 100 + year / 400;
322+
year += floorDiv(year, 4) - floorDiv(year, 100) + floorDiv(year, 400);
279323
month = <i32>load<u8>(tab + month - 1);
280324
return euclidRem(year + month + day, 7);
281325
}

std/assembly/index.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1756,7 +1756,10 @@ declare class Date {
17561756
setUTCSeconds(value: i32): void;
17571757
setUTCMilliseconds(value: i32): void;
17581758

1759+
toString(): string;
17591760
toISOString(): string;
1761+
toDateString(): string;
1762+
toTimeString(): string;
17601763
}
17611764

17621765
/** Class for representing a runtime error. Base class of all errors. */

0 commit comments

Comments
 (0)