How to convert an invalid date string to Javascript date - javascript

I fetch invalid date strings from the REST API but i may not fix the REST API. How can i format an invalid date strings like that "20180517T010237" ?
I tried to use moment for that, but i couldnt succeed.
let date = moment("20180517T010237", "YYYY-MM-DD T HH.mm.ss").toDate();
is there any easy way to do that?

The second string you pass moment is the format of the string you're parsing. Your format string has - and spaces that aren't in your input. Remove them:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Note that it will be parsed in local time. If you want UTC instead, use moment.utc:
let date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Example:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Related

How to add time zone to specific format in momentjs?

I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.

How to convert date time string in formatted date time in extjs

I have a string of Date and Time ("2017-11-29 11:08:43" YYYY-MM-DD hh:mm:ss) like this. I want to convert it into "29-11 11:08"(DD-MM hh:mm) format.
I tried it using below code. But not get any success. have you any solution?
convert: function (idleFrom) {
var date = Ext.Date.parse(idleFrom, "Y-m-d");
return date;
}
first change your string into date format using
var dt = new Date(idleFrom)
than change into you required format using
Ext.Date.format(dt, 'm/d/Y');
follw this link for more format
Hope it will work :)
If you have a string, and want it reformatted, you have to parse the string into a JS date object first, and then format the JS date object into the string representation you need:
var date = Ext.Date.parse("2017-11-29 11:08:43", "Y-m-d H:i:s")
var str = Ext.Date.format(date, "m/d/Y")
Please note that Ext.Date.parse is really picky regarding the format identifier. If the matching between the format identifier and the input string's format is not 100%, your date will be null.
E.g. Ext.Date.parse("2017-11-29 11:08:43", "Y-m-d H:i") will be null because the seconds are in the date string, but missing from the format identifier.

Convert into separate date and time into one string with format moment js

I am using moment js and new in this. So right now I am getting separated time and date from html to javascript controller so I want to convert into one string with format in moment js.
console.log($scope.timeTo);
console.log($scope.dateTO);
Console OutPut:
04:00
23/05/2017
But I want to set time and date together with momentjs.
Desired format:
2017-05-23T04:00:00
You can simply concat your strings and then parse it with moment.
Then you can use format() to get moment object in the format you need.
var timeTo = '04:00';
var dateTo = '23/05/2017';
var m = moment(dateTo + timeTo, 'DD/MM/YYYY HH:mm');
console.log(m.format('YYYY-MM-DD[T]HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Get date time in specific format in moment js

I am trying to get the date time in moment js in this format :
2016-12-19T09:43:45.672Z
The problem is I am able to get the time format as
2016-12-19T15:04:09+05:30
using
moment().format();
but I need the format as the first one [like .672Z instead of +05:30]. Any suggestions would be of great help.
From the documentation on the format method:
To escape characters in format strings, you can wrap the characters in square brackets.
Since "Z" is a format token for the timezone, you need to escape it. So the format string you are after is:
moment().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
As #VincenzoC said in a comment, the toISOString() method would also give you the format you are after.
Use moment.utc() to display time in UTC time instead of local time:
var dateValue = moment().utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):
var dateValue = moment().toISOString();
Try this
const start_date = '2018-09-30';
const t = moment(start_date).utc().format();
console.log(t);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
var dateTime = new Date("2015-06-17 14:24:36");
dateTime = moment(dateTime).format("YYYY-MM-DD HH:mm:ss");
Try this. You should have the date in the correct format.

Extract epoch from moment object

I am trying to extract the unix timestamp (epoch) from a date string as follows:
var week = $("#week").val();
var timestamp = moment(week).format("X");
console.log(timestamp);
This returns, in the console "Invalid Date".
I am passing the following format: "03-Nov-16"
I am trying to return the unix timestamp of a date.
Any help on this would be appreciated.
You need to tell moment the format of the date string you're trying to parse. I think you're looking for something like this (not tested):
var timestamp = moment("03-Nov-16", "DD-MMM-YY").unix()
See the official docs on date string parsing for more info.

Categories

Resources