Turn string into date - JavaScript - javascript

Hey guys I am retrieving a value from an input box and am using that value to turn into a Date for JavaScript the format is Y-m-d h:i:s. It works perfect in Chrome but any other browser says invalid Date
var old = $(".checked-in-time").val();
old = new Date(old);
UPDATE:
Here is what I am doing:
var current = new Date();
var old = $(".checked-in-time").val();
old = Date.parse(old , 'Y-m-d H:i:s');
var newEnd = current - old
minutes = parseInt((newEnd/(1000*60))%60);
var subtractedWaitTime = minutes;
Pretty much getting the time difference based on minutes.

Date.parse accepts a limited number of formats:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Your format is not one of the ones supported. You can parse it yourself and just pass the arguments directly. One of the forms Date accepts is this, which would be easy enough to pull out from your format:
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
But I would recommend removing the pain of having to worry about cross browser compatibility and parsing things yourself, and use moment instead, where you can parse the date like this
moment(dateStr,'YYYY-M-D H:m:s')
and then if you needed to have it as a Javascript Date object you could just run
moment().toDate();
in the more likely case you just need to display it formatted somewhere, or compare it to other dates, moment offers many functions for formatting, manipulating and comparing dates
http://momentjs.com/docs/#/displaying/as-javascript-date/

Try one of the following formats
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
Could be that some browsers don't support yyyy-mm-dd

You can parse date like this,
var old = $(".checked-in-time").val();
old = Date.parseDate(old , 'yyyy-mm-dd h:i:s');
if the above not working, you can also try Y-m-d H:i:s this format. For me Y/m/d H:i worked fine.

You could try use such format Y-m-dTH:i:s, e.g. 2011-01-01T12:00:00
Or you can use moment library (Javascript Date library)

Related

Weird ISO formatted Datestring to Javascript Date

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>

Convert string to date format using javascript

I have a string value and i need to convert that string value to the following date format using javascript.
var strDate = "2016-11-20";
expected output is: 20-Nov-2016
How Can I change this?
javascript have rich set of Date function e.g.:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
also already answered here :
Converting string to date in js
I have a UTC string and I want to convert it to UTC Date Object in JavaScript
We can mark this question duplicate
A little workaround could be the following, but if you have to manipulate dates a lot, I strongly recommend you to use the Moment.js library:
https://momentjs.com/
var strDate = "2016-11-20";
var utcDate = new Date(strDate).toUTCString();
var convertedDate= utcDate.substring(utcDate.lastIndexOf(", ") + 1, utcDate.lastIndexOf(" 00:"));
console.log(convertedDate.trim().replace(/\s/g, '-'));
Pay attention that the implementation of this method may change depending on the platform. Here from the official doc:
The value returned by toUTCString() is a human readable string in the
UTC time zone. The format of the return value may vary according to
the platform. The most common return value is a RFC-1123 formatted
date stamp, which is a slightly updated version of RFC-822 date
stamps.

Custom date format where type will be object and instance of date

I am receiving date from back end in 2017-03-02T08:12:22.997000+00:00 this format.
To display this date in specified format I am doing
new Date('2017-03-02T08:12:22.997000+00:00').toLocaleString() that gives 3/2/2017, 1:42:22 PM
There's one functionality which is sorting this formatted output.
Agenda is to sort the output based on 'date' type. But since I am using toLocaleString() method for formatting, sorting is done based on 'string' type.
Is there any solution where I can achieve 3/2/2017, 1:42:22 PM format and type will be a Date object?
Or a date format where I can see date along with time excluding GMT part? (like toUTCString())
Or any method from moment will work?
you can use moment.js which will give you moment object.
first convert date to IsoDate as moment.js latest version has deprecated moment constructor with illegal date string ( more info here )
var isoDate = new Date('2017-03-02T08:12:22.997000+00:00').toISOString(),
formatedDate = moment(isoDate).format('DD/MM/YYYY, HH:MM:SS A');
// formatedDate : "02/03/2017, 13:03:99 PM"
you may use Timezone for better handling of time -
moment(isoDate).tz('timezoneValue').format('DD/MM/YYYY, HH:MM:SS A');

Convert time zone of XML parsed time and date with moment.js

I'm parsing a XML file with Javascript and I would like to convert a date to my local time zone using moment.js but I'm stuck. The basic parsing consists of getting the date:
document.write(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue);
Which generates something like 31/12/2016 23:00. With moment.js it's possible to format the date like this:
var utcDate = moment.utc('31/12/2016 23:00', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write(localDate);
Which writes 01/01/2017 01:00 in my current time zone. But I can't figure out how to use the method above with the parsing. Tried modifying the variable but only getting "Invalid date" as a result.
var utcDate = moment.utc('x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write (localDate);
Does anyone have any tips? Might be other solutions than using moment.js but it seemed like the best and most flexible option.
You've put your XML traversal inside a string. That traversal won't happen if it's not actual javascript. Additionally, moment.js will try to parse that literal string as a date, NOT the value from that traversal.
'x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue'
You need to unquote your traversal to get its value, then feed that to moment.js.
var utcDate = moment.utc(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue, 'DD/MM/YYYY HH:mm');

javascript date format using dateFormat String

I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I
need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.
var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));
Which is the solution?
I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().
You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').
d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.
I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:
function toDate(str){
var months={
"JAN":1,
"FEB":2,
//... other months
"JUN":6,
//... other months
"DEC":12
}
var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
if(r.test(str)===false){
throw new Error("Invalid date string:"+str);
}
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2].toUpperCase()];
if(typeof m==="undefined"){
throw new Error("Invalid month name:"+arguments[2]);
}
var days=arguments[1]
m=(m<9)?"0"+m:m;
days=(days.length===1)?days="0"+days:days;
years=(years>50)?years="19"+years:"20"+years;
return m+"/"+days+"/"+years;
};
return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));

Categories