Weird ISO formatted Datestring to Javascript Date - javascript

I've got a Datestring like this one: 20171010T022902.000Z and I need to create Javascript Date from this string. new Date('20171010T022902.000Z') would return Invalid Date.
I saw that it's possible to use moment.js for this purpose but I am not sure how I would specify the according format for my given example. I found this example from another thread:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');
var jsDate = momentDate.toDate();
Question:
How can I create a JavaScript date from a given Datestring in this format: 20171010T022902.000Z (using moment)?

Your input (20171010T022902.000Z) matches known ISO 8601 so you can simply use moment(String) parsing method. In the Supported ISO 8601 strings section of the docs you will find:
20130208T080910.123 # Short date and time up to ms
Then you can use toDate() method
To get a copy of the native Date object that Moment.js wraps
Your code could be like the following
var m = moment('20171010T022902.000Z');
console.log( m.format() );
console.log( m.toDate() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Note that this code does not shows Deprecation Warning (cited in Bergi's comment) because you input is in ISO 8601 known format. See this guide to know more about this warning.
Moreover "By default, moment parses and displays in local time" as stated here so format() will show the local value for your UTC input (20171010T022902.000Z ends with Z). See moment.utc(), utc() and Local vs UTC vs Offset guide to learn more about moment UTC mode.

I think you can do this without moment.js,.
Basically extract the parts you need using regex's capture groups, and then re-arrange into a correct format for new Date to work with.
var dtstr = '20171010T022902.000Z';
var dt = new Date(
dtstr.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\.\d{3}Z)$/,
"$1-$2-$3T$4:$5:$6$7"));
console.log(dt);
console.log(dt.toString());
If you are using moment.js anyway, this should work ->
var dt = moment("20171010T022902.000Z", "YYYYMMDDTHHmmss.SSSSZ");
console.log(dt.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Related

Formatting ISO time with Luxon

Using Luxon JS, I've been trying to format datetime to output in a certain format, using the native toISO function:
This is what I get:
"2018-08-25T09:00:40.000-04:00"
And this is what I want:
"2018-08-25T13:00:40.000Z"
I know that they are both equivalent in terms of unix time and mean the same thing except in a different format, I just want to be able to out the second string rather than the first. I looked through the Luxon docs but was unable to find any arguments/options that would give me what I need.
As other already stated in the comments, you can use 2 approaches:
Convert Luxon DateTime to UTC using toUTC:
"Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
Use toISOString() method of JS Date.
You can use toJSDate() to get the Date object from a luxon DateTime:
Returns a JavaScript Date equivalent to this DateTime.
Examples:
const DateTime = luxon.DateTime;
const dt = DateTime.now();
console.log(dt.toISO())
console.log(dt.toUTC().toISO())
console.log(dt.toJSDate().toISOString())
console.log(new Date().toISOString())
<script src="https://cdn.jsdelivr.net/npm/luxon#1.26.0/build/global/luxon.js"></script>
From documentation I saw that in the method .fromISO of DateTime you can add an option object after the string of ISO date ("2018-08-25T09:00:40.000-04:00" in your example). In this object specify zone: utc like that:
const DateTime = luxon.DateTime;
const stringDate = "2018-08-25T09:00:40.000-04:00";
const dt = DateTime.fromISO(stringDate, {zone: 'utc'});
console.log('This is your date format', dt.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>

How to convert into Date time

When the date is passed from my c# to JavaScript it returns the date time as {4/3/2020 12:00:00 AM}
but in JavaScript it is shown as 1585852200000.
What is the format that is being used? And how can i convert it back?
You need to convert the Unix timestamp to DateTime format,
var localDate = new Date(1585852200000).toLocaleDateString("en-US")
console.log(localDate); // only local date
var localTime = new Date(1585852200000).toLocaleTimeString("en-US")
console.log(localTime) // only local time
// local datetime
console.log(new Date(1585852200000).toLocaleString());
1585852200000 is epoch date.
you can convert it as
var date = new Date(1585852200000)
console.log(new Date(1585852200000));
As an alternative from Shivaji's answer:
When you are passing the date through to JS you could cast it as a string with DateTime.ToString("dd/MM/yyyy") seen here on MSDN.
This will keep its integrity visually, if it is just for display purposes, otherwise you will need to re-cast appropriately in JS (in which case use Shivaji's answer).
JavaScript Date's object will return the DATE object and it's POSITION that is being assigned in your computer. So, when you are working with a date or datetime types, you can use some of the methods that are provided by the Date object, such as getDate() and getDay(). But, a better solution would be to format the Date object itself. For example: use the toString() or toUTCString() methods.
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Reference:
https://www.w3schools.com/js/js_date_formats.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

how to get only time from date in ISO formate

How to extract only time from the date which is present in ISO format?
I tried this:
var d = new Date('1970-01-15T03:32:12.000Z'); //ISO-8601 formatted date returned from server
console.log(d.getTime());// 1222332000
Expected op is : 03:32:12
Since your server returns an ISO-8601 formatted date which has a predefined format, you can convert it to ISO string using toISOString() and then get the substring of the time value:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.toISOString().substr(11,8));
Date.getTime() returns the time in UNIX epoch format.
https://en.wikipedia.org/wiki/Unix_time
To access only the parameters you are interested in, you can use Date.getMinutes(), Date.getMinutes(), etc. See docs on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Note: Do not forget to spend one thought on time zones when you work with Date
's time, especially when your app runs in different regions.
You have to manually build the time string using Date.prototype methods: getHours, getMinutes and getSeconds
Or use moment.js library.
Date.getTime() gives you the unix timestamp, which is the number of seconds since january 1st 1970;
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
from MDN
You need to format the date yourself, either by concatenating the output of the Date.getHours(), Date.getMinutes() and Date.getSeconds() methods, or by using one of the predefined formatting functions, like Date.toTimeString(). Checkout the docs to pick your choice.
You can use getHours(),getMinutes() and getSecondes(). Then you can use it with strings or objects.
Try the following:
d.toTimeString().split(' ')[0]
You can use moment.js to parse whatever format you like.
If you think moment.js is too big, there's another library call dayjs. The same fashion API but just 2KB. (Unfortunately, you can't do UTC time with dayjs yet.)
Update: Thanks kun for notifying the updates. You can now use UTC with dayjs plugin since v1.8.9.
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(moment(d).utc().format('HH:mm:ss'));
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs(d).utc().format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/plugin/utc.js"></script>

How can I convert this string representing a Date into an ISO 8601 compliant using JS?

I am not so into JavaScript and I have the following problem.
I have a JSON object like this:
{
"start_date": "2017-11-09 06:00:00"
}
Into a JavaScript script executed into the browser I do:
var dateCurrentOriginalForecast = new Date(currentOriginalForecast.start_date);
and it works fine: it creates a new Date object with the value related to 2017-11-09 06:00:00 date.
The problem is that I have to perform this JavaScript script into a Java application using Rhino (a JavaScript implementation that allows to perform JS code into a Java application) and here it cause an error:
TID: [-1234] [] [2017-11-09 11:10:08,915] INFO {org.apache.synapse.mediators.bsf.ScriptMessageContext} - dateCurrentOriginalForecast: Invalid Date {org.apache.synapse.mediators.bsf.ScriptMessageContext}
TID: [-1234] [] [2017-11-09 11:10:08,918] ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} - The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: RangeError: Date is invalid. (<Unknown Source>#137) in <Unknown Source> at line number 137
at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)
at javax.script.CompiledScript.eval(CompiledScript.java:92)
It seems that this date is invalid and it can't create the Date object.
From what I understood reading online the problem should be that old JS or Rhino (maybe the version of JS implemented by Rhino) does not support date of this type and probably I have to convert it in a date format which is fully compliant with ISO 8601
So I think that I have to convert my string 2017-11-09 06:00:00 into something like compliant with ISO 8601 standard.
I can't use third party library.
How can I do it?
Can use Date#toISOString() or Date#toJSON()
let d = new Date('2017-11-09 06:00:00')
console.log(d.toISOString())
console.log(d.toJSON())
//if you want convert date without convert in timezone than
var date = '2017-11-09 06:00:00';
var convertDate = date.replace(" ", "T"); // 2017-11-09T06:00:00
//if you want to convert in date with utc timezone
var date = new Date("2017-11-09 06:00:00").toISOString()
If I've understood your question correctly the problem is not so much that you need a ISO 8601 formatted date, but it is that you need to create a Date object from a date that is not formatted in ISO 8601. I personally would just use regular expression to parse the date into it's parts and then pass them into the Date constructor:
var currentOriginalForecast = {
"start_date": "2017-11-09 06:00:00"
};
var rxParseDate = /(\d{4})-(\d\d)-(\d\d)\s+(\d\d):(\d\d):(\d\d)/;
var dateParts = currentOriginalForecast.start_date.match(rxParseDate);
var year = dateParts[1],
month = dateParts[2],
day = dateParts[3],
hour = dateParts[4],
minute = dateParts[5],
second = dateParts[6];
var dateCurrentOriginalForecast = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
console.log(dateCurrentOriginalForecast);
Since there is no timezone mentioned in the start_date, I'm assuming it is UTC and converting it using Date.UTC and passing the resulting timestamp from that into the Date constructor. If start_date is in local time you would just remove Date.UTC and pass the parameters directly into the Date constructor. I'll also mention the month - 1; that is because the Date constructor (and Date.UTC) expect a 0-based month.

Converting date from string with offset to different timezone

I'm wondering on the correct way to convert a string date in a non-ISO format to a different offset/timezone.
I am currently given 3 values:
the date in format MM/DD/YYYY (23/11/2016)
the time in 24h format (23:13)
timezone offset (-07:00)
I would like to convert said date to the user's timezone.
I am trying to convert the format to the format accepted by moment timezone's moment.tz() function ('2016-11-23T23:13-07:00') but I am not sure how to do that without splitting the date array and converting it to said date.
Moment's timezone has the tools I need to convert the date afterwards to the local timezone. For example:
moment.tz('2016-11-23T23:13-07:00', moment.tz.guess());
Any thoughts on how to convert 23/11/2016 23:13 with offset -07:00 to the local date preferably using momentJS?
Why not just format as an ISO 8601 string with offset and give that to moment.js?
function customToISOString(date, time, offset){
return date.split(/\D/).reverse().join('-') + 'T' + time + offset;
}
document.write(customToISOString('23/11/2016','23:13','-07:00')); // 2016-11-23T23:13-07:00
Most modern browsers will also parse that, but don't do it as there are still plenty of older browsers around where it will fail.
I like Rob's answer, but I'll also give you it in moment.js.
First, you don't need moment-timezone, and you definitely don't need to guess the time zone id just to convert to that zone. In ISO format, it would just be like this:
var m = moment('2016-11-23T23:13-07:00');
This will read in the offset during parsing, apply it, then convert to the local time zone, returning a moment object in "local mode". This is the default mode, so it just works.
With the requirements you described it would be like this:
// your inputs
var d = "23/11/2016";
var t = "23:13";
var o = "-07:00";
var m = moment(d + ' ' + t + o, 'MM/DD/YYYY HH:mmZ');
Note that I add the space between the date and time just for safety, so there's no risk of mixing the year and the hour components.
Again it will automatically apply the offset and convert to the local time zone, since that's the default behavior. If you want some other behavior, there are ways to do that as well.

Categories