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().
Creates a Date object representing a specified time in ISO format.
//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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With