How to format date with date-fns? - javascript

I've been trying to format a date using date-fns but I keep failing. Basically I have it working just fine with momentJS but not with date-fns:
Here's my date:
"10-13-20" // month, day, and year
Now with momentJS it works just fine like this:
let result = moment("10-13-20", 'MM-DD-YY').format()
// result = "2020-10-13T00:00:00-06:00"
So I'm trying to do the same using date-fns but no luck. Can anyone point me in the right direction? Thanks in advance!
let result = format(new Date("10-13-20"), 'MM-DD-YY') // Not working

As you can see, with moment lib, we need 2 steps to get the result: parse string to Date object, then format date object to string.
Your code - format(new Date("10-13-20"), 'MM-DD-YY') is format step, try convert a date object to a string with format template is MM-DD-YY. But your date object is not correct.
The solution is doing the same with moment lib:
Parse date string to date object. Use parse
const dateString = '10-13-20';
const date = parse(dateString, 'MM-dd-yy', new Date()) // not MM-DD-YY
Format date object to result string. Use format
const result = format(date, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
console.log(result)
Result will be like (the same with moment's result in my timezone):
2020-10-13T00:00:00.000+09:00

const date = "2021-12-20"
console.log(format(parseISO(date), "dd-MM-yyyy"));
// output: 20-12-2021

Related

convert date string into the actual date format?

I have called an API and then get a date which is string format like '15/07/21-23:59:59'. But I want to convert this string into the actual date format like this:
**15/07/21** OR **2009-06-01T10:00:00.000**.
so how can I achieve this?
It's strange to see a response returning a formatted date expression. By the way, your task would be easily done with momentjs. Here is my snippet:
// since your date format is not a standard one, you would have to pass an
// instruction of your date format as a second parameter to the moment constructor
const momentDate = moment('15/07/21-23:59:59', 'DD/MM/YY-HH:mm:ss');
momentDate.format('DD/MM/YYYY'); // => "15/07/2021"
momentDate.format(`yyyy-MM-dd'T'HH:mm:ss.SSSZ`); // => "2021-07-Th'T'23:59:59.000+07:00"
you can pass this string to a Date object as follow:
var date = new Date(YOUR STRING);
or you can use Date.parse() method if it does not work:
Date.parse('04 Dec 1995 00:12:00 GMT');

Formatting ISO time with Luxon

Using Luxon JS, I've been trying to format datetime to output in a certain format, using the native toISO function:
This is what I get:
"2018-08-25T09:00:40.000-04:00"
And this is what I want:
"2018-08-25T13:00:40.000Z"
I know that they are both equivalent in terms of unix time and mean the same thing except in a different format, I just want to be able to out the second string rather than the first. I looked through the Luxon docs but was unable to find any arguments/options that would give me what I need.
As other already stated in the comments, you can use 2 approaches:
Convert Luxon DateTime to UTC using toUTC:
"Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
Use toISOString() method of JS Date.
You can use toJSDate() to get the Date object from a luxon DateTime:
Returns a JavaScript Date equivalent to this DateTime.
Examples:
const DateTime = luxon.DateTime;
const dt = DateTime.now();
console.log(dt.toISO())
console.log(dt.toUTC().toISO())
console.log(dt.toJSDate().toISOString())
console.log(new Date().toISOString())
<script src="https://cdn.jsdelivr.net/npm/luxon#1.26.0/build/global/luxon.js"></script>
From documentation I saw that in the method .fromISO of DateTime you can add an option object after the string of ISO date ("2018-08-25T09:00:40.000-04:00" in your example). In this object specify zone: utc like that:
const DateTime = luxon.DateTime;
const stringDate = "2018-08-25T09:00:40.000-04:00";
const dt = DateTime.fromISO(stringDate, {zone: 'utc'});
console.log('This is your date format', dt.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>

Formatting a Date String into a Date

I want to format a string Date "14/06/2019 12:52" using moment library in order to manipulate a Date object and not a string.
I tried using moment library but didn't succeed to have a Date object
const myDate = moment('14-06-2019 12:52')
the const myDate is not of type Date.
You need to provide the format also
const myDate = moment('14-06-2019 12:52', 'DD-MM-YYYY hh:mm');
You could use moment().toDate();
Refer here for more info http://momentjs.com/docs/#/displaying/as-javascript-date/

Parsing Time Variabale

I have a time stamp that i'm using for the x-axis of my line charts, as of now i'm just passing it as "2018-11-29T20:32:24.025Z" I would like to clean this up to only display the day, hour, and minute. It looks like Moment.js is a popular library for this, but i'm having some problems formatting it.
Failed Attempt
let parsedDate = moment(parsedData.published_at,'DD--hh--mm')
You need to
Parse the date
let parsedDate = moment(parsedData.published_at);
Format the date
let formattedDate = parsedDate.format(...
See the documentation.
If I understand your question correctly then you can pass your inputDate (ie 2018-11-29T20:32:24.025Z) directly to the moment constructor.
Doing this will give you a moment object for that inputDate string, and from that you can call format() with your DD--hh--mm pattern to format the required string:
let inputDate = "2018-11-29T20:32:24.025Z";
// Create a moment object from input string
let parsedDate = moment(inputDate);
// Format a string from moment, based on the required pattern
let formattedData = parsedDate.format('DD--hh--mm');
console.log(formattedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

What is the right way to pass a date as a string in a specific format and return a date object with momentjs?

I have been looking at the momentjs momenjs documentation because I want to use it to return a date object from a date that is a string in a particular format. My code looks like this.
const date = moment(stringDate, 'YYYY-MM-DD HH:MM:SS');
console.log(date);
But it creates an invalid date as can be seen here.
What am I doing wrong. How can I get a date object from a date string that is in a particular format?
You're using MM:SS for minutes:seconds, but it should be mm:ss; details here.
Example:
const stringDate = "2018-05-11 14:25:37";
// Parsing
const m = moment(stringDate, 'YYYY-MM-DD HH:mm:ss');
// Show it in a different format to demonstrate parsing worked
console.log(m.format("DD/MM/YYYY HH:mm"));
// Accessing the underlying Date object
const dt = m.toDate();
// Log that dateobject
console.log(dt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
In order to parse a string then return a different format you can:
> moment(dateString).format('DD.MM.YYYY')
Further examples:
Official docs: https://momentjs.com/docs/
Other sources: https://coderwall.com/p/vc3msa/a-very-short-introduction-to-moment-js

Categories