Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current date using date-fns in ISO-8601 format

I want to get a ISO-8601 format of last hour:minute:secounds from the current day using date-fns lib:

I'm using: endOfDay(new Date());

Fri Sep 14 2018 23:59:59 GMT-0300

So add toISOString() to get it in ISO format: endOfDay(new Date()).toISOString()

Result: 2018-09-15T02:59:59.999Z

When I need:

2018-09-14T23:59:59.999Z

like image 639
Joel Avatar asked Sep 14 '18 14:09

Joel


2 Answers

2018-09-14T23:59:59.999Z is not the end of day computed by endOfDay(new Date());. It is 3 hours earlier. The "Z" means UTC and your local time zone has the offset to UTC -0300.

By executing endOfDay you get a date value, which you can use in comparisons and other computations with other date values. It is a complete date with time in the local time zone.

Do you want to retain the same day number in the formatted string? You can format the date to an ISO 8601 string in your local time zone:

format(endOfDay(new Date()), 'yyyy-MM-dd\'T\'HH:mm:ssXX')
// Prints "2018-09-14T23:59:59.999-0300" in Brazil (BRT)

formatISO(endOfDay(new Date()))
// Prints "2018-09-14T23:59:59.999-03:00" in Brazil (BRT)

Do you want to get the end of the day with the same number as today in UTC? If you disregard the actual end of your day in relation to other dates, you can just concatenate the "last second of the day" with "Z" to it:

format(new Date(), 'yyyy-MM-dd') + 'T23:59:59.999Z'
// Prints "2018-09-14T23:59:59.999Z" anywhere on Earth

NOTE: If you use date-fns 1.x, use formats yyyy-MM-DD[T]HH:mm:ssZZ and yyyy-MM-DD in the patterns above. The syntax changed in 2.x versions. See also the supported patterns, which you can switch to your version of date-fns.

like image 114
Ferdinand Prantl Avatar answered Oct 17 '22 23:10

Ferdinand Prantl


format(endOfDay(new Date()), "yyyy-MM-dd'T'HH:mm:ss'Z'")

This method worked for me

like image 4
Srinivasan Mohan Avatar answered Oct 17 '22 22:10

Srinivasan Mohan