Try using utcToZonedTime()
To change the displayed date/time returned from format(), you must use either:
utcToZonedTime: when you want to know what the local date is in another timezonezonedTimeToUtc: when you want to know what a date in another timezone is in the local timezone
Working Demo
Answer from User863 on Stack OverflowVideos
» npm install date-fns
» npm install date-fns-tz
Copyconst [selected, setSelected] = React.useState(new Date());
const [timeValue, setTimeValue] = React.useState(format(selected, 'HH:mm'));
In the second line, the format(selected, 'HH:mm') will get the value of hours:minutes from the Date.
This is the easiest way.
This worked for me from: "17:00:00.000" to "05:00 PM"
Copyimport { format, parse } from "date-fns";
...
Copyconst time = '17:00:00.000';
...
Copy{format(parse(time.split(":", 2).join(":"), "HH:mm", new Date()), "hh:mm a")}
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 to do the same as 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-YYFormat 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
You need to parse it before formatting, and your format string is wrong. Check the parse docs
format(parse('18:54:00', 'HH:mm:ss', new Date), 'hh:mm:ss a')
// > 06:54:00 PM
This worked for me from: "17:00:00.000" to "05:00 PM"
import { format, parse } from "date-fns";
...
{format(parse('17:00:00.000'.split(":", 2).join(":"), "HH:mm", new Date()), "hh:mm a")}
The format tokens for date-fns can be found here: https://date-fns.org/v2.28.0/docs/format
const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'HH:mm')
This is also another option which uses 'kk:mm:ss' format:
const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'kk:mm:ss')