How to add specific characters in between values of a JavaScript date? - javascript

I am trying to format a date in JavaScript to fit a specific format.
My desired format is 29-Jan-2021
With the below code I have managed to generate "29 Jan 2021":
var newDate = new Date('2021-01-29T12:18:48.6588096Z')
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
};
console.log(newDate.toLocaleString('en-UK', options))
Can someone please show me how I can add - between the day, month, & year in the date above?

Well you if you have already able to find the string close to your answer you can achieve your solution with either of the two methods.
Either you can use replaceAll() or replace(). Both will be able to solve the issue.
let dateFormat = "29 Jan 2021"
console.log(dateFormat.replaceAll(" ","-")) // 29-Jan-2021
console.log(dateFormat.replace(/ /g,"-")) // 29-Jan-2021
Well I would suggest you to use replace() over replaceAll as some browsers do not support replaceAll(). Do check replaceAll support.

Related

UTC Date Time to Full Date in ES6

How can i convert this 2021-01-10 12:47:29 UTC to January 10, 2021?
I'm using this below using moment.js but this works browsers but not in Safari
{moment(video?.createdAt).format('MMMM D, YYYY')}
Moment.js is deprecated. Here's an alternative using native JS features.
First we need to convert the date string into a Date object. Calling new Date(video?.createdAt) is not reliable as mentioned on the Date() constructor page on MDN:
Parsing of date strings with the Date constructor
(and Date.parse(), which works the same way)
is strongly discouraged due to browser differences and inconsistencies.
See Date Time String Format on MDN for reference of the correct format. For example:
// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
const [date, time] = dateString.split(' ')
return new Date(`${date}T${time}.000Z`) // Z = UTC
}
Then we can use Date.prototype.toLocaleString() to format the Date object:
// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
const [date, time] = dateString.split(' ')
return new Date(`${date}T${time}.000Z`) // Z = UTC
}
function format(dateString) {
if (!dateString) return 'some fallback value'
const date = parseDate(dateString)
return date.toLocaleString('en', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
}
console.log(format('2021-01-10 12:47:29 UTC'))
//=> January 10, 2021, 2:47 PM
console.log(format(undefined))
//=> some fallback value
See Intl.DateTimeFormat() for all possible options. For example, these options produce slightly different results:
return date.toLocaleString('en', {
dateStyle: 'long',
timeStyle: 'short',
})
format('2021-01-10 12:47:29 UTC')
//=> January 10, 2021 at 2:47 PM
If the date strings can be in various formats, you probably need more robust date parsing. Or if you need exotic formattings, toLocaleString() might not meet your needs. In those cases, it might be useful to use one of the recommended Moment.js alternatives.
The new Intl DateTimeFormat API is gaining more support natively in many browsers, so it is a more future proof solution. As suggested in the doc, you can use polyfills for browsers which lack full support of this feature. Unfortunately, Safari is one of the browser which is yet to catch up.
A short snippet to achieve what you are looking for would be
new Intl.DateTimeFormat('en-US', { dateStyle: 'long'}).format(new Date("2021-01-10 12:47:29Z")) // outputs January 10, 2021
Keep in mind that date time string without Z at the end would be parsed as local time. Z means the date time supplied is UTC.
If you're searching for moment.js alternative, I would suggest date-fns. Here is a blog post that compares the 2 of them.
Here is the format documentation for date-fns.
So to answer your question using date-fns:
format(new Date(video?.createdAt), 'MMMM D, YYYY')

How to convert from date.now to pacific time

On my current project, I have to implement elapsed time for each user and display it on the webpage.
However, using the date.now will return utc and I would like to get it in pacific time. I googled and researched through online but could not get it to work... Is there a way to convert from utc to pacific time?
You can do something like this:
const event = new Date(Date.now());
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('us-PT', options));
Where "us" is the "United States" and "PT" is "Pacific-Time"
To see more go to MDN web docs Date.prototype.toLocaleDateString()
I see a few options you have at hand.
Option 1 - use an external library (moment / date-fns)
Consider using these libraries if your app is going to heavily rely on timezones, dates etc.
For example:
moment.tz(12345678, "America/Los_Angeles") // 12345678 being your Date timestamp
See more info here:
date-fns
moment
Option 2 - you need to use vanilla JS
Found a few answers on this thread, but I couldn't see any of them being long term reliable (because of savings time etc.) - I might be wrong about it, but I resort to date/time libraries when my app heavily uses the same.
This worked for me.
const date = new Date().toLocaleDateString('en-US', { timeZone: 'America/Los_Angeles' });
const time = new Date().toLocaleTimeString('en-US', { timeZone: 'America/Los_Angeles' });
const datetime = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles' });
Hope it helps others save time.

Any javascript library which can parse string created by Intl.DateTimeFormat?

Is there any javascript library which can parse string created by Intl.DateTimeFormat and give a Date?
For example:
options = {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
weekday: "short",
}
var test_date = new Date();
console.log(new Intl.DateTimeFormat('hr', options).format(test_date));
// note that test_date is just an example.
// We need to parse text created Intl.DateTimeFormat and give a Date.
will return:
sub, 21. ožu 2020. 12:41
That is great - exactly how it should be written.
But how to parse it back to be a Date?
Something like:
Date.parse('sub, 21. ožu 2020. 12:41', options, 'hr')
// hr is locale
// options are same a options given to Intl.DateTimeFormat
We tried momentjs and format 'llll', but sadly momentjs locale are different that Intl.DateTimeFormat implementation on Google Chrome (i.e., dots are added in wrong places, abbreviations for dates are incorrect, etc.). We tested with 'hr', 'sk', and few others and no luck :(
So is there any library which any javascript library which can parse string created by Intl.DateTimeFormat?

How to change the format of a date in JavaScript? [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
How to display a Date object in a specific format using JavaScript?
(7 answers)
Format a date string in javascript
(7 answers)
Closed 4 years ago.
I have a date formatted as 2018-06-13T13:28:14+0000, and I want to change it into this format 13/6/2018 1:28:14 PM.
Any suggestions will be helpful.
Thanks, in advance :)
Your date 2018-06-13T13:28:14+0000 is in UTC format.
One of the simplest options is to use momentjs to get desired date time format.
moment(yourDate).utc().format("DD/MM/YYYY hh:mm:ss a")
Below is code:
let date = moment("2018-06-13T13:28:14+0000").utc().format("DD/MM/YYYY hh:mm:ss a")
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
the toLocaleString() function with the en-USlocale is close to what you are searching for. Would this be enough for you ? It will give you back something like :
today.toLocaleString("en-US");
// will give you => 6/15/2018, 9:03:58 AM
If you really need no comma, then use the toLocaleString() and then remove the comma like :
today.toLocaleString("en-US").replace(',','');
see : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleString
To format a Date in javascript you can use Date.toLocaleDateString() method, it will give you many options to format dates.
This is a sample code snippet, you could use:
var d = new Date();
var options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
};
console.log(d.toLocaleDateString('fr-FR', options));
Note:
Of course , you can play with options to get more possible results, you can check that in the Docs as well.
Otherwise, as suggested, you can use a JS library like Moment.js or date-format, they have better enhanced features.

How to get date in specific locale with JavaScript?

I need to get the date in a specific locale using JavaScript - not necessarily the user's locale. How can I do this?
I did some research and found date.getUTCMonth() and date.getUTCDate(). How can I use this or something else to get the date in a certain locale?
You can use toLocaleDateString:
From the MDN documentation:
The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));

Categories