Convert string to ISODate - javascript

How could I convert the string "2015-02-02" to ISODate 2015-02-02T00:00:00.000Z? I was trying to find some example but did not.

You can use the regular Javascript date functionality for this
new Date(dateString).toISOString()
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
However, date parsing is very inconsistent across browsers so if you need this to be robust I would look into parsing using for example with Moment.js as this will allow you to specify a format string by which the date should be parsed like such
date = moment("12-25-1995", "YYYY-MM-DD");
date.format(); //will return an ISO representation of the date
from: http://momentjs.com/docs/#/parsing/string/

To change "2015-02-02" to "2015-02-02T00:00:00.000Z" simply append "T00:00:00.000Z":
console.log('2015-02-02' + 'T00:00:00.000Z');
Parsing to a Date and calling toISOString will fail in browsers that don't correctly parse ISO dates and those that don't have toISOString.

new Date("2015-02-02").toISOString()

new Date("11/11/2019").toISOString()
or use it as a variable
mydate = "11/11/2019"
new Date(mydate).toISOString()

Related

How to manipulate date time using vanilla javascript

I want to manipulate date which come from the api.
When I use: console.log(dataAPI.dateStation)
I see 2023-01-24T06:00:00.000Z
Is there way to change the date time in this format 2023-01-24 06:00:00
Just I want to remove T character between date and time and remove .000Z at the end.
The simplest way to do it is probably:
new Date(dataAPI.dateStation).toLocaleString()
If what you want is to display it somewhere, it'll automatically adapt the ISO date you have into a localized and readable date (based on timezone and language).
To know more about it and the options, here is the doc: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
If you want to print the date in ISO 8601 format, you can use the 'sv' (Sweden) locale and Date.toLocaleString().
You can also specify whichever IANA timezone you wish to use, I'm using UTC in this case.
const d = '2023-01-24T06:00:00.000Z'
let timestamp = new Date(d).toLocaleString('sv', { timeZone: 'UTC' });
console.log('Timestamp:', timestamp);
Use the javascript date class with toLocaleString
new Date(dataAPI.dateStation).toLocaleString('en-US');
Without installing some third-party library, your best bet is probably to use the string you have (which is the format returned by toISOString() ),and modify it as desired. If it's already a string in the format you gave, you can just call replace on it:
dataAPI.dateStation.replace('T',' ').replace('.00Z','')
If it's a Date object, first call toISOString() to get a string:
dataAPI.dateStation.toISOString().replace('T',' ').replace('.00Z','')
If it's a string in a possibly-different format, call new Date() to get a Date object, then call toISOString() on that, and finally call replace on the result:
new Date(dataAPI.dateStation).toISOString().replace('T',' ').replace('.00Z','')
You can use regular expressions to remove the parts you don't want:
let s = "2023-01-24T06:00:00.000Z"
s = s.replace(/T/, ' ')
s = s.replace(/\.\d{3}Z$/, '')
console.log(s)

Date ISO date string issue

console.log(new Date('2016-05-24').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/26/2016').toISOString()); // '2016-05-23T23:00:00.000Z' // why?
I am sending data to the server to parse and want to ensure that server will encode my date correctly.
What is the simplest way to convert date to string as '2016-05-24T00:00:00.000Z' in both cases?
Thanks
console.log(new Date('2016-05-24 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/24/2016 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
Append the timezone to the date before creating a new date object so that the string parsing code in the Date constructor doesn't get confused. Always disambiguate if possible.
Your code was using different timezones for each parse because of the way the dates were formatted. One was using +0 timezone, other was using -1 timezone hence the date being pulled back an hour when the ISO string was created.
One is parsing in UTC time, one is parsing in local time.
new Date('2016-05-24').toISOString() // '2016-05-24T00:00:00.000Z'
new Date('05/24/2016').toISOString() // '2016-05-24T07:00:00.000Z'
Playing around, here's one solution:
new Date(new Date('05/24/2016') - (new Date()).getTimezoneOffset() * 60000).toISOString() // '2016-05-24T00:00:00.000Z'
The strategy:
Create the new offset date
Subtract the offset
Create a new date from that result
Reference links:
javascript toISOString() ignores timezone offset
Why does Date.parse give incorrect results?
On further consideration, I'd recommend parsing the date string into something that is "universal" before passing it to the date constructor. Something like:
var tmp = ('05/24/2016').split('//');
var universal = [tmp[2], tmp[0], tmp[1]].join('-'); // 2016-05-24
...
Also, Moment.js does this sort of thing very neatly.
Use the getDate(), getMonth() and getFullYear() methods to strip out what you need.

Javascript - reformat date string to ISO8601

I have a string like this:
21.03.2016 23:59
And I need this string converted into a ISO-8601 date-time string:
YYYY-MM-DDTHH:mm:ss+00:00
Is there a simple way to convert this date?
I try it whit moment.js but i can't find a function to parse an existing date.
You can also do this without using moment.js.
Look code as following:
(new Date("03.21.2016 23:59")).toISOString()
just you need to change your string 21.03.2016 23:59 (dd-mm-yyyy) to 03.21.2016 23:59 (mm-dd-yyyy). You can easily do this by split the date and change the order of split part.
And if you dont want to do this then simply use moment.js as per matthias's answer.
Using moment.js you could do:
var dateString = '21.03.2016 23:59';
var momentDate = moment(dateString, 'DD.MM.YYYY HH:mm');
console.log(momentDate.toISOString());
Here is a fiddle showing this.

Convert YYYY-MM-DD HH:MM:SS to different format in Javascript

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");

How to convert time and date string to ISO format

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!

Categories

Resources