JavaScript Lessons

JavaScript Date Formatting: Methods and Examples

See how JavaScript handles date formatting with toDateString, toUTCString, and ISO strings, and learn when to use each format.

Serhat ALPASLAN2 min read

Contents

javascript operatorler

JavaScript Date Formats

If we want to print the date with JavaScript and don’t apply any formatting, we get output similar to the following. As you’ve noticed, this formatting isn’t very useful. This format is called ISO format. Of course, this depends on where you’ll use the date format. So in this case, we need to understand and learn date formats well.

Sat Jan 01 2000 03:00:00 GMT+0300 (Turkey Standard Time)

If we wanted to write it in millisecond format, we’d get output like the following. Also, when we want to print a date in milliseconds, it calculates from January 1, 1970 00:00:00 as the starting date. Example: 946684800000

Format Output Example
ISO format “2021-02-09” (International standard)
Short date format “02/09/1981”
Long date format “Mar 12 2021” or “12 Mar 2021”
Full date format “Wednesday March 25 2001”

toUTCString

When the shown code sample is run, an output like “Sun, 26 Sep 2021 10:21:44 GMT” is displayed.

var tarih = new Date();   
alert(tarih.toUTCString());

toDateString

When the following code is run, you’ll get output similar to “Sun Sep 26 2021”.

var tarih = new Date();   
alert(tarih.toDateString());

One of the points you shouldn’t forget is that JavaScript doesn’t run server-side, so you’ll see your computer’s date information on screen.

ISO Format

The ISO date format is ISO 8601, and its notation is YYYY-MM-DD. It’s generally used when we need to write a date to a database.

alert(Date("2021-02-09"));

When we run the code above, it will convert it to the format “Sun Sep 26 2021 13:31:15 GMT+0300 (GMT+03:00)” and print it to the screen in this format. When using the ISO format, you can also write it without specifying the day or month, or as date, hour, minute, second.

alert(Date("2021-02"));
alert(Date("2021"));

YYYY-MM-DDTHH:mm:ssZ can also be written. Note that the date and time are separated by the letter T. The Z at the end indicates that it’s in ISO date format.

alert(Date("2021-02-09T12:00:00Z"));

Short Date Format

The short date format notation is MM/DD/YYYY.

alert(Date("02/09/2021"));

Long Date Format

If we want to write the date format in long form, it’s MMM DD YYYY.

alert(Date("Mar 15 2021"));

Full Date Format

The date format written in long form can be considered the full date.

alert(Date("Sun Mar 10 2021 03:00:00 GMT+0300 (Türkiye Standart Saati)"));

Share it if it helped

Write a comment