Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date-fns: Difference between parseISO(string) and new Date(string)?

Tags:

date-fns

I'm trying out date-fns v2.

I got some errors when I ran:

parseISO("Apr 9, 2020, 12:00:00 am");

or

parseISO("Apr 9, 2020, 12:00:00 am", "MMM M, YYYY, hh:mm:ss aaaa");

but this worked fine:

new Date("Apr 9, 2020, 12:00:00 am");

I'm trying to understand when I should use one or the other but I couldn't find the docs for parseISO().

like image 250
Dev01 Avatar asked Jul 01 '19 16:07

Dev01


People also ask

What is Parseiso?

Creates a Date object representing a specified time in ISO format.

How can I get current date in FNS?

//import the function you want to use const {format} = require('date-fns'); const {format} = require('date-fns'); //today's date const today =format(new Date(),'dd. MM. yyyy'); console.

What is the use of date-fns?

date-fns supports both TypeScript and Flow. The typings are generated from the source code and bundled with the package, so they're always up-to-date. The functional programming submodule provides a better alternative to chaining: composition; which makes your code clean and safe and doesn't bloat your build.

How do you convert a string to a date in Javascript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object.


1 Answers

Docs for parseISO here. Basically parseISO tries to parse string which holds ISO formatted date string like '2019-09-25T14:34:32.999Z'.

What you are trying to parse is internationalized string. I.e. 'Apr 9, 2020, 12:00:00 am' is US locale formatted date string.

new Date() works because it relays on locale of your environment (browser or node), the string you are passing to it is matching format of your locale. If you will pass french locale formatted date string, will most likely fail.

To parse internationalized string, you may also look at parse which will also take the format of passed date string.

If you pass your dates over the wire (like HTTP rest API or database) you should be already decided on format to pass/store your date times. Normally it is either ISO formatted date string, number of milliseconds in UTC since 1970 or any other suitable for your case. Then as per specification of your "wire" or "store", you will do parseISO or new Date(milliseconds).

If you do some browser based web app, you should be considering the local of your user. Then parsing may become cumbersome, as you have take care of locale and/or timezone of your user.

like image 106
muradm Avatar answered Sep 18 '22 13:09

muradm