Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add leading zeroes to date

I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

var MyDate = new Date(); var MyDateString = new Date(); MyDate.setDate(MyDate.getDate()+10); MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear(); 

I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.

if (MyDate.getMonth < 10)getMonth = '0' + getMonth; 

and

if (MyDate.getDate <10)get.Date = '0' + getDate; 

If someone could show me where to insert these into the script I would be really appreciative.

like image 795
Julian Coates Avatar asked Aug 31 '10 00:08

Julian Coates


People also ask

How do you add leading zeros to a date?

Show activity on this post. var MyDate = new Date(); var MyDateString; MyDate. setDate(MyDate. getDate() + 20); MyDateString = ('0' + MyDate.

Should dates have leading zeros?

In many -- possibly most -- calendar date picker widgets for U.S. users which display the selected date in month/day/year format, leading zeroes are shown when showing a single-digit month and/or day value. For example, the date March 1, 2018 would be rendered as 03/01/2018 .


2 Answers

Try this: http://jsfiddle.net/xA5B7/

var MyDate = new Date(); var MyDateString;  MyDate.setDate(MyDate.getDate() + 20);  MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'              + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'              + MyDate.getFullYear(); 

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09" 

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2) "09" 

But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010" 

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2) "10" 
like image 94
user113716 Avatar answered Nov 07 '22 14:11

user113716


The modern way

The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to achieve the desired result:

const date = new Date(2018, 2, 1) const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument   year: "numeric",   month: "2-digit",   day: "2-digit", }) console.log(result) // outputs “01/03/2018”

Or using a Temporal object (still in proposal, caniuse):

const date = new Temporal.PlainDate(2018, 2, 1) // also works with zoned date const result = date.toLocaleString("en-GB", { // you can use undefined as first argument   year: "numeric",   month: "2-digit",   day: "2-digit", }) console.log(result) // outputs “01/03/2018” 

When you use undefined as the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.

Performance

If you plan to format a lot of dates, you should consider using Intl.DateTimeFormat instead:

const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me   year: "numeric",   month: "2-digit",   day: "2-digit", }) const date = new Date(2018, 2, 1) // can also be a Temporal object const result = formatter.format(date) console.log(result) // outputs “01/03/2018”

The formatter is compatible with Date and Temporal objects.

Historical dates

Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so:

const date = new Date() date.setFullYear(18, 2, 1) // the year is A.D. 18 

This is not required for Temporal objects, but years below 1000 will not contain leading zeros in all cases, because the formatter (that is shared for the Date and Temporal API) does not support 4-digit formatting at all. In this case you have to do manual formatting (see below).

For the ISO 8601 format

If you want to get your date in the YYYY-MM-DD format (ISO 8601), the solution looks different:

const date = new Date(Date.UTC(2018, 2, 1)) const result = date.toISOString().split('T')[0] console.log(result) // outputs “2018-03-01”

Your input date should be in the UTC format or toISOString() will fix that for you. This is done by using Date.UTC as shown above.

Historical dates for the ISO 8601 format

Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so to be used for the ISO 8601 format:

const date = new Date() date.setUTCFullYear(18, 2, 1) // the year is A.D. 18 

Note that the ISO format for Temporal objects with dates before the year 1000 or after the year 9999 will have a different formatting compared to the legacy Date API. It is recommend to fallback to custom formatting to enforce 4 digit years in all circumstances.

Custom 4-digit formatting on the year

Sadly, the formatter doesn't support leading zeros on the year. There is no 4-digit option. This will remain for Temporal objects as well, because they do share the same formatter.

Fortunately, the ISO format of the Date API will always display at least 4 digits on the year, although Temporal objects do not. So at least for the Date API you can format historical dates before the year 1000 with leading zeros by falling back to a manual formatting approach using part of the ISO 8601 format method:

const date = new Date() date.setUTCFullYear(18, 2, 1) const ymd = date.toISOString().split('T')[0].split('-') const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}` console.log(result) // outputs “01/03/0018”

For a Temporal object a different route is necessary, since the ISOYearString will be formatted differently for dates before the year 1000 and after the year 9999 as mentioned before:

const date = new Temporal.PlainDate(2018, 2, 1) // also works with zoned date const zeroPad = (n, digits) => n.toString().padStart(digits, '0'); const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`; console.log(result) // outputs “01/03/0018” 

Miscellaneous

For the Date API there is also toLocaleTimeString, that allows you to localize and format the time of a date.

like image 32
Martin Braun Avatar answered Nov 07 '22 14:11

Martin Braun