how to Convert Date into ISO Date Format in javascript - javascript

i have a date like this which i should convert them into ISO format
const date = 05/23/2022;
i need like this
2022-05-23T00:00:00Z

Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.
let date = '24.05.2022 0:00:00';
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

You can use String.split() to get the day, month and year for the Date in question.
We can then pass to the Date.UTC() function and then the Date() constructor. (Note: We pass monthIndex to the Date constructor, that's why we subtract 1 from the month )
To display as an ISO string, we can then use Date.toISOString()
const [month, day, year] = '05/23/2022'.split('/');
const date = new Date(Date.UTC(year, month - 1, day));
const result = date.toISOString();
console.log('Date (ISO):', result);
We can also do this easily with a Date / Time library such as luxon.
We'd use the DateTime.fromFormat() function to parse the input string, setting the timezone to 'UTC'.
To output the ISO date, we can use the DateTime.toISO() function:
const { DateTime } = luxon;
const date = DateTime.fromFormat('05/23/2022', 'MM/dd/yyyy', { zone: 'UTC'});
console.log('Date (ISO):', date.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
We can also do this in moment.js, using moment.utc(), then .toISOString():
const date = moment.utc('05/23/2022', 'MM/DD/YYYY');
console.log('Date (ISO):', date.toISOString())
<script src="https://momentjs.com/downloads/moment.js"></script>

Related

Covert date to epoch timestamp using Javascript

I have date in MM/DD/YYYY HH:MM AM/PM format
Example 07/27/2022 10:36 AM
I want to convert it into Epoch timestamp which is 1658898360
You can use the date.getTime method to convert it to epoch:
const date = new Date("07/27/2022 10:36 AM");
console.log(date.getTime() / 1000)
Just be sure that you (or the client) is in the same timezone you are expecting (IST in this case).
Or just add GMT+5:30 to ensure this.
const date = new Date("07/27/2022 10:36 AM GMT+5:30");
console.log(date.getTime() / 1000)
The Date object in Javascript is notoriously tricky to work with, and date parsing is sadly lacking. Simply using
const dateString = "07/27/2022 10:36 AM"
const date = new Date(dateString)
might work, but not reliably.
One option is to use the date-fns library:
import { parse, getUnixTime } from 'date-fns'
const date = parse('07/27/2022 10:36 AM', 'MM/dd/yyyy hh:mm a', new Date())
const epoch = getUnixTime(date)
You can use below sample code:
function epoch (date) {
return Date.parse(date)
}
const dateToday = new Date()
const timestamp = epoch(dateToday)
console.log( timestamp )

How to convert into Format 2016-10-19T08:00:00Z with momentjs

in a project we are using momentjs with date. And from backend we become the date in the following format: 2016-10-19T08:00:00Z (don't ask me why...)
Now we are setting a new date in frontend from some selectboxes. And I am trying to convert this in the same format:
const date = '25.03.2021';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
// trying to convert to 2021-03-25T13:45:00Z
rawDate.format(); // output: 2021-03-25T13:45:00+00:00
rawDate.format('DD.MM.YYYY hh:mm:ss'); // output: 03.01.2022 08:00:00
rawDate.format('DD.MM.YYYY hh:mm:ss z'); // output: 03.01.2022 08:00:00 UTC
rawDate.format('DD.MM.YYYY hh:mm:ss Z'); // output: 03.01.2022 08:00:00 +00:00
rawDate.toISOString(); // output: 2022-01-03T08:00:00.000Z
I know I could probably just use format() or toISOString() and slice/replace the last bit. But I like to know is there a way without any string concat/manipulation?
You could use moment.utc() to ensure your date is in UTC, then use .format() with the format string DD-MM-YYYYTHH:mm:ss[Z].
I'd also suggest explicity defining the format you are parsing from in the moment() call, e.g. pass 'DD.MM.YYYY' as the second argument.
The reason the backend takes dates in this format is that it's a standardized way of formatting dates to make them machine-readable and consistent (ISO 8601)
const date = '25.03.2021';
const hour = '13';
const minute = '45';
// Raw date will be in the UTC timezone.
const rawDate = moment(date, 'DD.MM.YYYY').hour(hour).minute(minute).utc();
console.log(rawDate.format('DD-MM-YYYYTHH:mm:ss[Z]'));
<script src="https://momentjs.com/downloads/moment.js"></script>
You can try convert to UTC ..?
i.e. Do you intend to make use of a UTC date/time..?
const date = '2021-03-25';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
const utc = moment.utc(rawDate);
console.log(rawDate.format('DD.MM.YYYY hh:mm:ss'));
console.log(utc.format()); //2021-03-25T11:45:00Z

How to convert format date to dd/mm

Heloo, i want to convert format date 2022-04-09 08:00:33 to format 9 April. i was trying to convert it, but the format still wrong, thanks for help me before
#solved
When it comes to date manipulation in JavaScript, there are a lot of third-party libraries available. Some of the most popular options are Moment.js and Day.js. When it comes to formatting a date into a custom format, these libraries are really easy to use.
Example:
moment('2022-04-09 08:00:33','YYYY-MM-DD HH:mm:ss').format('D MMMM')
converts:
2022-04-09 08:00:33 to 9 April
You can visit the link to see available formats.
Or You can use a simple solution that involves native date class:
const date = new Date().toLocaleDateString('en-gb', {
day: 'numeric',
month: 'long',
});
console.log(date)
but for this input date should be in proper date format i.e., ISO String of timestamp in milliseconds.
The arrangement of day and month will be according to locale you use.
export const formatDate = (date) => {
const newDate = new Date(date)
const month = newDate.toLocaleString('default', { month: 'long' })
const day = newDate.getDate()
const formated = `${day} ${month}`
return formated
}

MomentJS converts my date to UTC by default

I got an issue related to momentJS
I have the following date '09/27/2021 00:00:00 'which is already in UTC timezone. However when I use the following function
const date = moment(someDate, 'MM/DD/YYYY HH:mm:ss').valueOf();
I'm getting 1632718800000 as timestamp value. But when I do the inverse process I'm getting '10/27/2021 05:00:00 "
How can I avoid momentJS to convert my date to UTC by default?
You can use moment(x).local()
const someDate = '09/27/2021 00:00:00';
const date = moment(
someDate,
'MM/DD/YYYY HH:mm:ss'
);
// get timestamp
const timestamp = date.valueOf();
// revert datetime from timestamp
const dateFromTimeStamp = moment(timestamp);
console.log(dateFromTimeStamp.local().format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Proper way to parse a date as UTC using date-fns

I have a log file with some timestamps
2020-12-03 08:30:00
2020-12-03 08:40:00
...
I know from the log provider's documentation that the timestamps are written in UTC (although not using ISO format)
Now I want to parse them with date-fns :
const toParse = "2020-12-03 08:40:00"
parse(toParse, 'yyyy-MM-dd HH:mm:ss', new Date()).toISOString()
And because the locale of my computer is in UTC+1 here is what I see:
> "2020-12-03T07:40:00Z"
expected:
> "2020-12-03T08:40:00Z".
Here is the hack I currently use to tell date-fns to parse as UTC :
const toParse = "2020-12-03 08:40:00"
parse(toParse + '+00', 'yyyy-MM-dd HH:mm:ss' + 'X', new Date()).toISOString()
And as expected,
> "2020-12-03T08:40:00Z".
Is there any proper way of doing this using date-fns? Looking for an equivalent to moment's moment.utc()
I don't know about "proper", but you can use zonedTimeToUtc to treat a timestamp as having any offset or timezone you like, including UTC, e.g.
// Setup
var {parse} = require('date-fns');
var {zonedTimeToUtc} = require('date-fns-tz');
// Parse an ISO 8601 timestamp recognised by date-fns
let loc = 'UTC';
let s1 = '2020-12-03 08:30:00';
let utcDate = zonedTimeToUtc(s1, loc);
// Show UTC ISO 8601 timestamp
console.log(utcDate.toISOString()); // "2020-12-03T08:30:00.000Z"
// Parse non–standard format yyyyMMdd
let s2 = '20210119';
let fIn = 'yyyyMMdd';
let d = zonedTimeToUtc(parse(s2, fIn, new Date()), loc);
console.log(d.toISOString()); // "2021-01-19T00:00:00.000Z"```
You can test it at npm.runkit.com/date-fns.
I think you are looking for parseJSON, which supports a number of formats (but does not let you specify the source format).
Converts a complete ISO date string in UTC time, the typical format for transmitting a date in JSON, to a JavaScript Date instance.
import { parseJSON } from 'date-fns';
const utcDate = parseJSON('2020-12-03 08:40:00');
// Thu Dec 03 2020 19:40:00 GMT+1100 (Australian Eastern Daylight Time)
Example of using parse and zonedTimeToUtc
it('should parse polish date', async () => {
expect.assertions(1)
const dateWithoutTime = '29 gru 2003'
const parsed = parse(dateWithoutTime, 'd LLL yyyy', new Date(), {
locale: pl,
})
const dateUTC = zonedTimeToUtc(parsed, 'UTC')
expect(dateUTC.toISOString()).toStrictEqual('2003-12-29T00:00:00.000Z')
})

Categories