How to modify date format taken from Wordpress API? - javascript

By taking data from Wordpress API I'm getting date/time this way - 2019-11-29 19:00:00
How to modify it by making look like this - November 29, 2019 19:00
HTML:
<p class="date">DATE</p>
JS:
const date = postCopy.querySelector(".date");
date.textContent = post.event_date

I suggest using the toLocaleDateString() method available in vanilla JS.
Relevant doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
let initialDate = "2019-11-29 19:00:00"
let formattedDate = new Date(initialDate).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit',
hour: "2-digit",
minute: "2-digit",
hour12: false
})
console.log(formattedDate)
If you don't like this approach, take a look at the 51 solutions proposed in this similar question: How to format a JavaScript date

Related

redefine Date() javascript

The official calendar of our country is jalali!
Jalali is a type of calendar that has a mathematical relationship with the Gregorian calendar.
I want to change Date() in JS to returns jalali values.
there are many lib or func for this, but I don't want use them.
Can I redefine Date()?
Where can I view Date() source?
You can use toLocaleDateString();
let today = new Date().toLocaleDateString('fa-IR');
console.log(today);
fa-IR is for Farsi-Iran, but all the ISO country codes can be found here
also you can set options as second argument, for example:
let options = { year: 'numeric', month: 'long', day: 'numeric' };
new Date().toLocaleDateString('fa-IR', options);
Don't mess with objects you don't own. You can create your own date object called maybe jDate (after "jalali date", which I assume is the same as the Intl object's "persian" calendar) and implement methods there.
The Intl.DateTimeFormat constructor returns an object that has a formatToParts method that you can leverage to implement the Date methods you need, then you can work on a standard Date object underneath but return Jalali values from the methods. e.g. to get all the current date parts in English:
let f = new Intl.DateTimeFormat('en-GB-u-ca-persian',{
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
});
console.log('Current Jalali date: ' + f.format(new Date()));
console.log('The parts:');
f.formatToParts(new Date()).forEach(part => console.log(part.type + ': ' + part.value));
For some things you have to run the format method more than once with different options, e.g. to get both the month name and number as both are specified by the month option: month: 'long' for the name and month: 'numeric' for the number.

How to format the date to (dd/mm/yyyy hh:mm:ss)

How can I convert the date below into this template (dd/mm/yyyy hh:mm:ss) ?
05/04/2021 14:52
I tried to do it that way, but I only get the time and not the date with time.
var data = new Date('05/04/2021 14:52');
var time = data.toLocaleTimeString('pt-PT', {hour12: false});
console.log(time);
You can use below script
var data = new Date('05/04/2021 14:52');
console.log(data.toLocaleString('en-GB',{hour12: false}));
Output : "04/05/2021, 14:52:00"
If you need more date-related staff than simple date formatting, you can use Moment.js.
moment().format('MMMM Do yyyy, h:mm:ss a'); // April 5th 2021, 9:16:13 pm
moment().format('DD/MM/yyyy hh:mm'); // 05/04/2021 21:18
If you need to format your date object, simply use:
moment(date).format('DD/MM/yyyy hh:mm');
Moment.js is also useful for operation on dates like days, week, month adding/subtracting, getting the start of a week, month, quarter, and many other useful operations.
This is my solution. If you want to create a advanced format, you can read more about object Intl
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
const formatDate = new Intl.DateTimeFormat("en" , {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
console.log(formatDate.format(new Date('05/04/2021 14:52')))

Intl.DateTimeFormat returns an hour over 24

I have the following Unix timestamp: 1611328500000 (Fri Jan 22 2021 10:15:00 GMT-0500 (Eastern Standard Time)).
I need to display it in Korean Standard Time. To do so, I'm using Intl.DateTimeFormat. However, for some reason, the result I'm getting is 24:15 when I attempt to format it. Unless I'm delusional, I'm pretty sure that's higher than a 24-hour clock usually goes (0:00 to 23:59).
Google tells me my result should be 0:15, obviously on the following date (Sat Jan 22).
Here's a minimal working example:
const date = new Date(1611328500000);
const timeOptions = {
hour12: false,
hour: '2-digit',
minute: '2-digit'
};
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Seoul', ...timeOptions
});
console.log(formatter.format(date));
Am I crazy? Can times go up to 24:15 in some circumstances? What is happening here?
EDIT: I just found this page which seems to be experiencing a similar problem. The answer provided there points me towards something called hourCycle, with a link to MDN's Intl.DateTimeFormat.
However, hourCycle only appears once on that page, in the browser support section. Adding the suggested hourCycle: h11 to my timeOptions did not work.
Digging further, I found this page, which lists h23 as a valid option. Surely this is what I'm after! But, alas... my result is still 24:15.
Switch from hour12: true to hourCycle: 'h23' to display the hours from 00:00 to 23:59.
const date = new Date(1611328500000);
const timeOptions = {
hourCycle: 'h23',
hour: '2-digit',
minute: '2-digit'
};
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Seoul', ...timeOptions
});
console.log(formatter.format(date));
I used the below code and it worked to transform the input 3000000 milliseconds to the output 00:50:00.000Z
const dateInMilliseconds = 3000000
const formatterConfig = {
hour: "numeric",
minute: "numeric",
second: "numeric",
hourCycle: "h23",
timeZone: "UTC",
fractionalSecondDigits: 3
}
const dateInFormat = new Intl.DateTimeFormat([], formatterConfig).format(dateInMilliseconds)+'Z';
// 00:50:00.000Z

convert string date and time to utc based on timezone using moment

am using moment in nodejs server to convert local time from frontend to utc.
my time format is date = '10-07-2020 08:45 PM' in string format. When i use moment(date).format() its converting format to this 2020-10-07 20:45:00+05:30 timezone is adding based on server and i have timezone = '+4:00' this is my local timezone. I would like to convert my date string to UTC based on the timezone field not based on the server timezone. How can I do this?
I tried the following methods but am not getting a proper solution
moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')
Anyone Please suggest
You can use moment-timezone to create a date from a string and a certain timezone. In order to do that you need to specify your format and the corresponding timezone. Something like this:
const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
Instead of moment, perhaps use intl DateTimeFormat?
Here are some possibilities
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', };
const date = new Date('10-07-2020 08:45 PM')
console.log(date)
options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

Convert JS date format into localized human readable format

How should I convert a date format of YYYY-MM-DD into a human readable format %e %B %Y in JS by taking into an account a different language from system's locale?
In PHP it would be like
<?php echo trim(strftime('%e %B %Y', strtotime('2019-07-31'))); ?>
// Renders: 31 July 2019
I want to have the same, but with a corresponding language locale, for example "French format" so it will become : 31 Juillet 2019
==== UPDATED ====
As mention by #Baljinder Singh, solution below from the link, works perfectly
console.log(
new Date('2019-07-31').toLocaleDateString('fr-FR', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
)
If it's browser-specific then you can make it dynamic with window.navigator.language.
const date = new Date('2019-07-31').toLocaleDateString(window.navigator.language, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
console.log(date);
Notice: Working fine in chrome and firefox.
Try
let d = new Date('2019-08-20');
let s = d.toLocaleDateString(navigator.languages,{day:"numeric", month:"long", year: "numeric"});
console.log(s);

Categories

Resources