JavaScript Scratches

Dates and Times

The date objects in JavaScript are automatically converted to a string, with the toString() method.

JavaScript stores dates as number of milliseconds since January 01, 1970.

What's so special about that date? January 1, 1970, is known as the Unix Epoch, the point where time starts for Unix-based systems.

A number you may need: one day (24 hours) is 86,400,000 milliseconds.

Dates & times are created and mangled using the Date class. A new Date object is created using the Date() constructor.

Months and days are indexed beginning with 0.

Without any argument (pun), the Date constructor returns the complete, current date and time.

var RightNow = new Date();
Sprint(RightNow + " is the time right now!<br/>");

Pulling apart a date string can be fully accomplished - the get methods are your friends.

getYear() is deprecated. Use the getFullYear() method
setYear() is deprecated. Use the setFullYear() method
toGMTString() is deprecated. Use the toUTCString() method
let ThisDate="December 12, 1987";
let Year = ThisDate.getFullYear();
Sprint("ThisDate: "+ ThisDate + "<br>";
let ThisYear = ThisDate.getFullYear();
let ThisMonth = ThisDate.getMonth();
let ThisDay = ThisDate.getDate();
Sprint("ThisDate: "+ ThisDate + "<br/>");
Sprint("Just the year: "+ Year + "<br/>");
Sprint("The month: "+ ThisMonth + "<br/>");
Sprint"And the day: "+ ThisDay + "<br/>");

Note that pulling the day number was done using get.Date NOT get.Day.

get.Day() does something a bit different - it gets the day number of the week.

Also note that 'December' was returned as the 11th month, because months are also zero-indexed.

Days and months are zero-idexed:
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6

January = 0
February = 1
March = 2
April = 3
May = 4
June = 5
July = 6
August = 7
Semptember = 8
October = 9
November = 10
December = 11

Using getDay for the above would give us:

So, December 12, 1987 was a Saturday. Yep, it was: Epoch Converter

Getting previous values before 1900 is done using some of the available methods:

let LongAway = new Date(1748, 3, 25); // AP 25, 1748
Sprint("<br/>Year:", LongAway.getFullYear());
Sprint("<br/>Month:", LongAway.getMonth()); // 3 (AP)
Sprint("<br/>Day:", LongAway.getDate());
Sprint("<br/>Milliseconds since epoch:", LongAway.getTime() + "<br/>"); // Will be a negative number

The full Date-Time reference should answer any questions you have.

Date Math