How to convert "2016-02-23T11:31:36.23" into JavaScript object? - javascript

I am trying to convert string from the following format into JavaScript Date() object. Then I want to change the format into mm/dd/yyyy h:MM AM/PM using the jquery-dateFormat UI
2016-02-23T11:31:36.23
I tried to do this
function formatDateTime(str) {
var dt = new Date(str);
return $.format.date(dt, "mm/dd/yyyy h:MM TT");
}
But this is giving me this 00/NaN/NaN NaN:NaN TT
How can I correctly convert the string into a date object?
According to the documentation I should be able to convert isoDateTime into an object just like I have done

You can parse de string into a new date and use toLocaleDateString (plain js):
var strdate = "2016-02-23T11:31:36.23";
var date = new Date(Date.parse(strdate));
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' };
console.log(date.toLocaleDateString('en-US', options));
Fiddle on: https://jsfiddle.net/fcLkrwv6/

Related

Prepending text to html elements using a Javascript function

I'm trying to use Javascript for formatting the time to a localized format using Intl.DateTimeFormat method.
I have several instances of time strings in 24h format i want to localize in a HTML page, for example:
<span class="timeclass">18:45</span> //and so on..
And i am able to format the time with the following code, which uses a Date object:
let locale = 'en-US'; // this variable changes, example 'en-UK', etc
let time = new Date('1971-12-12T18:45');
console.log(new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
}).format(time)); //output is "6:45 PM"
As the code shows, i added a dummy date in order for the Date object to be semantically correct. Now, i'm trying to write a function to replace all instances of times contained within timeelem classes:
var locale = 'en-US';
var timeformat = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
});
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
timeelements.textContent= timeformat.format(timeelements.textContent);
});
But it is not working because it is getting the time in the format 18:45 instead of 1971-12-12T18:45. What is the best way to prepend such dummy date to the string? The date is only relevant for the localization function to work, by the way.
You can choose any date you want, as long as it is in the correct format. You can do something like this: WORKING DEMO
HTML
<span class="timeclass">18:45</span>
<span class="timeclass">18:15</span>
<span class="timeclass">11:45</span>
<span class="timeclass">02:45</span>
<span class="timeclass">22:45</span>
<span class="timeclass">23:45</span>
<span class="timeclass">18:00</span>
JAVASCRIPT
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
console.log("elem ", element.innerHTML);
// Append any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z')
.toLocaleTimeString({}, {
timeZone: 'UTC',
hour12: true,
hour: 'numeric',
minute: 'numeric'
});
element.innerHTML = timeString12hr
});
------------------------UPDATED------------------------
var locale = "en-US";
var timeformat = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
});
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
console.log("elem ", element.innerHTML);
const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z');
element.innerHTML = timeformat.format(timeString12hr)
});

Print JavaScript date in 'MMM dd, yyyy' format (like 'Oct 17, 2012') [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)
Closed 1 year ago.
I am getting a date string in ISO format (for example, '2012-10-16T17:57:28.556094Z'), but while printing it in my html page I should print it in 'MMM dd, yyyy' format (for example, 'Oct 17, 2012').
What is the simplest way to achieve this without using any library?
Thanks.
You can use toLocaleDateString().
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
const date = new Date(),
dateString = date.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'});
console.log(dateString);
You can use the Intl.DateTimeFormat for this (in supporting browsers).
You create a formatter with the options you want, in your case, the year should be "numeric", the month "short" and the day "numeric".
You can construct a date object using your ISO8601 string and then pass it to the formatter.
const formatter = new Intl.DateTimeFormat("en", { year: "numeric", month: "short", day: "numeric" });
const date = new Date("2012-10-16T17:57:28.556094Z");
formatter.format(date);
// => 'Oct 17, 2012'
Alternatively, you could set up an array of month names and use the getMonth, getDay and getFullYear methods of Date, like so:
const months = ["Jan", "Feb", ... , "Dec"];
const date = new Date("2012-10-16T17:57:28.556094Z");
`${months[date.getMonth()]} ${date.getDay()}, ${date.getFullYear()}`;
// => 'Oct 17, 2012'
Use Date.parse() to convert the string to a Date object, then extract the relevant data into a format string if none of the canned formats match (toDateString(), toLocaleString() etc).

Formatting date with EJS/Node.js

I have a string with the following format:
2020-05-01T23:59:59
And I'd like the output to be formatted like so:
May 1, 2020 - 11:15pm
But I'm finding all kinds of conflicting info and nothing seems to be working.
Here, you have two options:
The first, and probably easier of the two options is to use a library like moment.js, which can easily achieve this like so:
moment().format("MMM D, YYYY - hh:mma")
// Should produce May 1, 2020 - 11:15pm
Or, if you must use vanilla JS, or are reluctant to install another package, you can do the following:
const currentDate = new Date();
const dateFormatter = new Intl.DateTimeFormat("en-us", {
month: "long",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true
});
const dateParts = Object.fromEntries(dateFormatter.formatToParts(currentDate).map(({ type, value }) => [type, value]));
const dateString = `${dateParts.month} ${dateParts.day}, ${dateParts.year} - ${dateParts.hour}:${dateParts.minute}${dateParts.dayPeriod.toLowerCase()}`;
// dateString should now contain the string May 1, 2020 - 11:15pm

Convert ISO string to specific date format

I need to display date in a certain format in application. I have input of '2009-04-01' as string and I want this format April 1, 2009 using Javascript.
Create a Date object:
const date = new Date('2009-04-01');
Format the Date using toLocaleString:
date.toLocaleString('en-us', { month: 'long', day: 'numeric', year: 'numeric' });
Just create a new Date object and then use that to format the output:
d = new Date("2009-04-01")

Convert Date of Birth to Javascript Date

I have a standard date in ISO format: 1950-01-01 (date of birth)
And I need to convert it to a javascript object, so I can convert it to US Format (01/01/1050).
However when I convert it, it changes it to: Sat Dec 31 1949 17:00:00 GMT-0700
I just need it converted, without any offsets, or changes. If they were born on x day, it is x day.
Here is what I am doing currently:
$("#dob1").val( new Date(client.dob1).toLocaleDateString('en', { day: '2-digit', month: '2-digit', year: 'numeric' }) )
client.dob1 = "1950-01-01"
Final working result, in case anyone stumbles upon this:
$("#dob1").val( new Date(client.dob1).toLocaleDateString('en', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: "UTC" }) )
You can also replace the dashes with slashes, and make a new Date() from the resulting string.
(some code from https://stackoverflow.com/a/29185654/2033574)
// Manually
date1 = new Date("1950/01/01")
// Or programmatically:
dashDate = "1950-01-01"
date2 = new Date(dashDate.replace(/-/g, '/'))
// Same output
document.write(date1 + "<br>" + date2)
You can simple create a Date object like this.
new Date('2015-10-13')
You can read here more about Date

Categories