javascript date - javascript time - what day is it - what time is it

Javascript What Time Is It? What’s Today’s Date?

Getting the current date and time is a very common need of Javascript programmers. Formatting the new date information for a variety of needs (and international locales) comes close behind. In this blog post we’ll cover aspects of the Javascript current date time challenges and both standard and home-grown solutions.

What follows is a targeted view into the more general topic of Javascript Date — Creating, Getting, and Setting Time. See that blog post for more details.

A Date Versus How It Appears

The first stumbling block with date-time concepts is what a date actually is versus how it appears (or how it’s used). Since childhood we’re taught to think of “the time” as a text string, like “6 o’clock” or “6:00 PM”, but as programmers we learn that date-time is stored within a Javascript Date object and how the date-time value is displayed is dictated by our needs.

This is a much more actionable point of view, as we can now do things like showing how the current time appears in Nawiliwili Harbor, Kaua’i, Hawai’i or in the Tankwa Karoo, South Africa. We can calculate what time it’ll be in an hour and a half, and the elapsed time between two Date objects.

Basic Creation and Printing a Javascript Date Object

As mentioned, all Javascript date and time information is stored in the Date object, created by:

let d = new Date() ;

For consistency and ease of reading the component computations below, the actual Date object was created with a fixed time. (See the details below, in the Universal Coordinated Time section.) Running any of these code snippets will of course display the current date-time.

Printing the Date object to the Javascript console log:

console.log( d ) ;

results in a date-time string:

Thu Jan 01 1970 13:14:15 GMT-0800 (Pacific Standard Time)

(This happens to be an RFC 5322 format string plus a timezone name. There are many standardized formats in use.)

Printing Date-Times, The Proper Way

While one can extract and format individual components of the Date object (as will be shown below) the most direct way to print date-time information in a standardized, easily-maintainable manner is via the Intl.DateTimeFormat() function, specifying

  1. the locale (a combination of ISO 639-1 language code and ISO 3166-1 alpha-2 country code
  2. a dateStyle (short, medium, long, or full)
  3. a timeStyle (same options apply)

Available are the combinations and permutations of the following:

dateStyletimeStyle
short1/1/701:14 PM
mediumJan 1, 19701:14:15 PM
longJanuary 1, 19701:14:15 PM PST
fullThursday, January 1, 19701:14:15 PM Pacific Standard Time

A call to the Intl.DateTimeFormat() function looks like:

console.log(
new Intl.DateTimeFormat(
'en-US',
{ dateStyle: 'short', timeStyle: 'long' }).format(d) );

When the locale is en-US (English-US) the output is Jan 1, 1970, 1:14:15 PM; when it’s en-GB (English-Great Britain) it becomes 01/01/1970, 13:14:15 Pacific Standard Time.

Printing Date-Times, Piecemeal

Should it be necessary to extract components of the Date object, the following table shows the various functions, their return values, and the result when applied to our existing object:

functionreturn valuesresult
date.getDate()day of month (1-31)4
date.getDay()day of the week (from 0-6)1
date.getFullYear()year — use getFullYear() instead of the deprecated getYear1970
date.getHours()hour (from 0-23)13
date.getMilliseconds()milliseconds (from 0-999)0
date.getMinutes()minutes (from 0-59)14
date.getMonth()month (from 0-11)0
date.getSeconds()seconds (from 0-59)15
date.getTime()number of milliseconds since UNIX epoch (midnight 1 Jan 1970)76455000
date.getTimezoneOffset()minutes between UTC time and local time480

In practical terms, every programmer that’s “rolled their own” time-date strings has gone through some of the following steps. (Note, it’s much faster, easier, and more maintainable to use the functions described above.) To get human-readable days and months, two arrays are needed.

let days = new Array( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ) ;

let months = new Array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ) ;

The order of the array elements corresponds to the return values of getDay() and getDate(), respectively. Next, we need a function to return the ordinal for the day of month value:

function ordinal_of(i) {
    var j = i % 10, k = i % 100 ;
    if (j == 1 && k != 11) { return "st" ; }
    if (j == 2 && k != 12) { return "nd" ; }
    if (j == 3 && k != 13) { return "rd" ; }
    return "th";
}

To recap the date value, we set a known value to make reading this blog consistent. In real-world use the parameters would be omitted.

let d = new Date(1970, 0, 1, 13, 14, 15, 0);
console.log( "d is '" + d + "'" ) ; // --> d is 'Thu Jan 01 1970 13:14:15 GMT-0800 (Pacific Standard Time)'

dayOfWeek is assigned the array value corresponding with the return from getDay():

let dayOfWeek = days[ d.getDay() ];
console.log( "dayOfWeek is '" + dayOfWeek + "'" ) ; // --> dayOfWeek is 'Thursday'

Likewise, the month is assigned the array value corresponding with the return from getMonth():

let month = months[ d.getMonth() ];
console.log( "month is '" + month + "'" ) ; // --> month is 'January'

The ordinal is the result of the function ordinal_of() when given the day of the month:

let ordinal = ordinal_of( d.getDate() ) ;
console.log( "ordinal is '" + ordinal + "'" ) ; // --> ordinal is 'st'

Universal Coordinated Time

When logging activities occurring across various time zones it’s handy to keep things pegged to Universal Coordinated Time (also known as UTC, for temps universel coordonné). Compare the standard method of creating a date:

let d = new Date( 1970, 0, 1, 13, 14, 15, 0 ) ;
 
console.log( d ) ; // --> Thu Jan 01 1970 13:14:15 GMT-0800 (Pacific Standard Time)

with using the Date.UTC() function. Note that the time zone location of the user (taken from the web browser) is preserved and the time is adjusted to UCT. Times captured from users in different time zones around the globe are now relative and can be compared easily.

let u = new Date( Date.UTC( 1970, 0, 1, 13, 14, 15, 0 )) ;
 
console.log( u ) ; // --> Thu Jan 01 1970 05:14:15 GMT-0800 (Pacific Standard Time)

Conclusion

This blog post covered the Javascript challenge of getting the current date and time and printing it in a variety of formats. Printing becomes more critical as international users use your software as each country has their own conventions and expectations on how times, dates, (and monies) are displayed.

Start Learning

To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.

Source Code

Complete source code, when needed to expand upon the snippets above, will be included below, ready for use in an online Javascript tester like PlayCode.