I have a date string with this format
2016-08-12T15:22:43.698Z
how can I parse it to obtain a resulting string that looks like
Aug 12, 2016 5:22 PM
Is there libraries/component that could facilitate such operation or shall I do it manually by coping each part of the String?
var date = new moment('2016-08-12T15:22:43.698Z');
console.log(date.format('MMM DD, YYYY h:mm A'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
Use momentjs, and format the moment obj as your requirement.
If the string is in the ISO standard format, which it looks like it is, you can use Date.parse() or new Date() to turn the value into a Date object. With a Date, you can call toString() or toLocaleString() to get the date formatted in local time.
If you are targeting modern JavaScript environments, Intl.DateTimeFormat provides a very complete API for formatting the date in different locales.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
Related
I'm working on a project right now where I want to get an array of dates between two end points. I've got that code working perfectly when I hard code the start and end date in.
My problem is when I used an input, the code doesn't work. How can I convert a normal date input into a UTC string?
Here's an example of what I'm on about: https://jsfiddle.net/mksvh95y/5/
<input type="date" id="bubbles" placeholder = "enter date">
<button onclick="getDate()"> Click me to get date</button>
<script>
function getDate(){
var water = document.getElementById("bubbles").value;
alert(water);
//alert(water.toUTCString());
var fire = new Date (2018,10,15);
alert(fire);
}
I want the get the 'water' variable to be formatted like the 'fire' variable.
I saw there's .toUTCstring(), but that doesn't work
This is possibly a duplicate of Why does Date.parse give incorrect results, but here's an answer that may be more suitable.
The value of a date input is an ISO 8601 format date string in the format "YYYY-MM-DD", which is what you should see from:
alert(water); // something like 2018-06-21
The format of the string returned by Date.prototype.toString is implementation dependent (though ECMAScript 2019 will standardise it). That's the format you're getting from:
alert(fire) // e.g. Thu Jun 21 2018 00:00:00 GMT+1000 (AEST)
One fix is to convert the string from the date input to a Date, then use the default toString for both outputs. But your problem then is that parsing of the ISO 8601 date string is UTC, so the dates will be different by the host timezone offset, e.g.
console.log(new Date('2018-06-21').toString()); // 21 Jun 2018
console.log(new Date(2018, 5, 21).toString()); // 21 Jun 2018
So you need to parse the string from the input as local using a simple function like:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
console.log(parseISOLocal('2018-06-21').toString());
console.log(new Date(2018, 5, 21).toString());
If you want to use a library like moment.js, it will parse ISO 8601 formatted date strings as local (which is consistent with ISO 8601), then convert it to a plain Date and use the default toString, e.g.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date"
onchange="console.log(moment(this.value).toDate().toString())">
I strongly recommend using the excellent MomentJS library for date mainpulation, as native support is poor:
function getDate(){
var water = document.getElementById("bubbles").value;
var waterMoment = moment(water);
alert(water.utc().format()); //outputs a UTC date string
var fire = new Date (2018,10,15);
alert(fire);
}
See the moment.utc() function and the moment.format() function for more details.
I am trying to parse the String date format(yyyyMMddThhmmssZ) to Date.
const date = Date.parse("20171201T120000Z");
console.log(date );
Result is ...
NaN
Could you teach me the smartest way?
Ideally, you should try to standardize the date string in a way that works best for your needs. As the MDN states, parsing a date from a string is problematic in general.
Date.parse()
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
Although your date format is valid ISO 8601 as illustrated in the comments by #duskwuff, it is not supported by Date.parse.
It seems the version specified here by ECMAScript is supported, YYYY-MM-DDTHH:mm:ss.sssZ, but not a format like 20180131T011614Z as you are using. It seems Date.parse only supports a simplification of the ISO 8601 format.
A library like moment.js is helpful as it can parse a wide range of date formats automatically (including your valid ISO 8601 date) or you can even specify your date format explicitly if you wanted.
moment('20171201T120000Z', 'YYYYMMDDTHHmmssZ').toString()
"Fri Dec 01 2017 06:00:00 GMT-0600"
moment('20171201T120000Z').toString()
"Fri Dec 01 2017 06:00:00 GMT-0600"
Though, for your example, you could parse out the date without moment.js
let dateString = '20171201T120000Z'
let [_, year, month, day, hour, min, sec] = dateString.match(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/)
// month is 0-based so subtract 1
new Date(year, month - 1, day, hour, min, sec)
Could you teach me the smartest way?
I would say the "smartest way" can vary wildly based on your circumstances.
Do you control the source of these date strings?
Are the date strings coming from another system?
Are users entering these date strings?
As long as you use some standard (even if it's not supported directly by Date.parse), then I would say the parsing can be done with whatever method works best for you. A library like moment, manually parsing the elements of the date, translating your date to epoch or a format recognized by Date.parse, or whatever you prefer.
I used materialize datepicker to pick a date in french format. Now I need this date formatted back to a date object so I can use it in my api. Here's how I try to convert the date back to a normal format:
moment("dimanche 30 juillet 2017","dddd D MMMM YYYY").locale('fr').toDate();
But I receive Invalid Date. Is there a way to convert this date back using moment? Or can I somehow hook to materialize component to retrieve a normal date?
You need to set the fr locale before attempting to parse french day/monthnames.
moment.locale('fr');
moment("dimanche 30 juillet 2017","dddd D MMMM YYYY").toDate();
You can parse your input string passing locale parameter, see moment(String, String, String) docs:
As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().
Here a working sample:
var m = moment("dimanche 30 juillet 2017", "dddd D MMMM YYYY", 'fr');
console.log(m.toDate());
console.log(m.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
For further info see Changing locale globally and Changing locales locally.
I have a string in javascript as 2016-02-27 20:24:39 and I want to convert this as 27th Feb 08:24pm.
What is the easiest way to do in Javascript?
Checkout the JavaScript library called moment.js.
Since the default format for moment is ISO 8601 (YYYY-MM-DD HH:MM:SS), you don't need to tell moment how to parse the input String date (it defaults to ISO 8601), so you can simply write:
var now = "2016-02-27 20:24:39";
var formattedDate = moment(now).format("Do MMM HH:mma");
console.log(formattedDate);
Demo:
https://jsfiddle.net/gekd97dy/
More information about displaying in different formats can be read here:
http://momentjs.com/docs/#/displaying/
There is a non-standard Date method toLocaleFormat('%d-%b-%Y'). But appears to only work in Firefox for now.
Better use the date.format library (only 125 lines)
var date = new Date('2016-02-27 20:24:39');
dateFormat(date, "dS mmm, h:MMTT");
I have two inputs, a time and a date input. I'm trying to format them as an ISO string to send to the backend using moment.js.
This is what I have so far 01:00 2016-01-01, I need to format or convert that to ISO. Is there a way to do it using Moment?
To convert ISO I recommend the more standard
date.format();
or
JSON.stringify(yourDate)
or if you prefer momentjs:
var date = moment();
date.toISOString();
or
moment(yourDate).format('MM/DD/YYYY'); // <- your custom format string
To know what are the momentjs formatting rules start reading here
Assuming you are referring to ISO8601 and momentjs (2.10.6), I currently do it like this
var example = momentObject.format("YYYY-MM-DD[T]HH:mm:ss");
You need to use moment's parse function to first create the correct moment object from the data that you have (assuming a 24-hour clock, and month listed before the days):
var myMoment = moment("01:00 2016-01-01", "HH:mm YYYY-MM-DD");
Then you can use moment's format function to output the date in the ISO format that you want. Note that calling the format function without any parameters will output ISO 8601 by default:
myMoment.format();
See the moment docs for more info here.
Hope this helps!