Convert milliseconds string to date in javascript - javascript

There were a lot of answered questions about converting milliseconds to date format but none of them was able to solve my problem.
I have a string (and not a time) coming in my javascript code. It is of the format as below
1380549600000+1000
When I try to parse it using the following code it gives me "invalid date" error.
My main objective is to convert this string to dd/mm/yyyy format. So was thinking of converting it into date and applying methods like "getMonth", etc
<script>
var modDate = "1380549600000+1000"; //Note the value is in "" hence a string
var d = new Date(modDate); //Invalid date error here
document.getElementById("demo").innerHTML = d;
</script>
The following works just fine. But this is not the format I am getting.
<script>
var modDate = 1380549600000+1000; //Note the value is no longer in ""
var d = new Date(modDate); //No problems here
document.getElementById("demo").innerHTML = d;
</script>
Please help.
Thanks in advance.
Cheers.

edit:-
eval is not the best approach, it is not safe to use eval, so use this instead:-
var modDate = "1380549600000+1000"
var temp = modDate.split("+");
modDate = parseInt(temp[0]) + parseInt(temp[1]);
I am not sure if you need that added 1000, if you don't, it could be done in one line as :-
modDate = parseInt(modDate.split("+")[0])
older approach :-
<script>
var modDate = eval("1380549600000+1000"); //Note the value is in "" hence a string
var d = new Date(modDate); //Invalid date error here
document.getElementById("demo").innerHTML = d;
</script>

Other approach w/o using eval:
var modDate = "1380549600000+1000";
var d = new Date(modDate.split("+")
.map(parseFloat)
.reduce(function(a,b){return a + b;}));

Use parseInt to get the numeric value of the string (safer than eval, but same premise):
modDate = (isNaN(modDate)) ? parseInt(modDate, 10) : modDate;
if !isNaN(modDate) {
var d = new Date(modDate);
document.getElementById("demo").innerHTML = d;
} else {
console.log("Value in modDate not a number");
}

I had to use a bit of a mishmash of the answers here to get mine to work.
My Date value was being sent to my web page as a String, like so: "/Date(978278400000-0500)/"
So I parsed it like this, to get it to display as a valid date:
// sDateString = "/Date(978278400000-0500)/";
var modDate = sDateString.replace(/[\/Date\(\)]/g, "");
return new Date(parseInt(modDate, 10));
//returns: Sun Dec 31 2000 11:00:00 GMT-0500 (Eastern Standard Time) {}

Related

Parsing a date in javascript

First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601

How can I get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

how to parse milliseconds into date in javascript

i am getting stucked to convert date from ms (receiving from json)
i was recieving the date in json in format below
/Date(1355250600000)/
so that i converted it into ms --->
var d = response.ContributionsDate.replace("/", "").replace("/", "").replace("Date(", "").replace(")", "");
so now its d = 1355250600000
to convert i tried the code below--->
var date = new Date(d);
alert(date);
but did not work (invalid date), if anyone have any idea about date parsing, help me
d is a string, not a number.
Try
var date = new Date(+d);
instead.
The prefix + causes coercion to a number.
Incidentally, you can simplify your replace operations to
var d = +response.ContributionsDate.match(/^\/Date\((\d+)\)\/$/)[0];

CDate for Javascript

I have been using CDate in my program and the worry part is , it works only in IE.
cdate(strValue) . If I pass the value of strvalue as 01/02 , it returns as Wed Jan 2 etc . Am looking for the same implementation in javascript so that it will work in other browsers. Am trying my best to find one, but am not lucky. Can anyone tell me what api we can use in javascript instead of using CDate ??
You can try the following code:
var comp = "05/04".split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var date = new Date(null, m - 1, d);
date.toDateString(); //this line will return the date
Now you can parse the string and manipulate string according to your need.

Javascript JSON Date parse in IE7/IE8 returns NaN

I'm parsing a date from a JSON event feed - but the date shows "NaN" in IE7/8:
// Variable from JSON feed (using JQuery's $.getJSON)
var start_time = '2012-06-24T17:00:00-07:00';
// How I'm currently extracting the Month & Day
var d = new Date(start_time);
var month = d.getMonth();
var day = d.getDate();
document.write(month+'/'+day);// "6/24" in most browsers, "Nan/Nan" in IE7/8
What am I doing wrong? Thanks!
In older browsers, you can write a function that will parse the string for you.
This one creates a Date.fromISO method- if the browser can natively get the correct date from an ISO string, the native method is used.
Some browsers got it partly right, but returned the wrong timezone, so just checking for NaN may not do.
Polyfill:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Result:
var start_time = '2012-06-24T17:00:00-07:00';
var d = Date.fromISO(start_time);
var month = d.getMonth();
var day = d.getDate();
alert(++month+' '+day); // returns months from 1-12
For ie7/8 i just did:
var ds = yourdatestring;
ds = ds.replace(/-/g, '/');
ds = ds.replace('T', ' ');
ds = ds.replace(/(\+[0-9]{2})(\:)([0-9]{2}$)/, ' UTC\$1\$3');
date = new Date(ds);
This replaces all occurrences of "-" with "/", time marker "T" with a space and replaces timezone information with an IE-friendly string which enables IE7/8 to parse Dates from Strings correctly. Solved all issues for me.
See RobG's post at Result of toJSON() on a date is different between IE8 and IE9+.
Below function worked for me in IE 8 and below.
// parse ISO format date like 2013-05-06T22:00:00.000Z
function convertDateFromISO(s) {
s = s.split(/\D/);
return new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
}
You can test like below:
var currentTime = new Date(convertDateFromISO('2013-05-06T22:00:00.000Z')).getTime();
alert(currentTime);
I suggest http://momentjs.com/ for cross browser date issues.
#gib Thanks for the suggestion on Moment.js. This small library really helps out with dealing with dates and JavaScript.
Moment.js solved the problem described in the original question that I was also having. IE8 was displaying JSON ISO dates as NaN when parsed into a new Date() object.
Quick solution (include moment.js in your page, or copy the code to your js functions include)
If you just need to display a date on your page, loaded from a JSON ISO date, do this:
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.calendar()); //use Moment's relative date function to display "today", "yesterday", etc.
or
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.format('m/d/YYYY')); //use Moment's format function to display "2/6/2015" or "10/19/2014", etc.
If you must have a Date() object (say for use with jQuery Components), do the following so successfully populate your JSON provided ISO date. (This assumes you are already inside the function of handling your JSON data.)
var ship_date = new Date(moment(data.ShipDate).format('m/d/YYYY')); //This will successfully parse the ISO date into JavaScript's Date() object working perfectly in FF, Chrome, and IE8.
//initialize your Calendar component with the "ship_date" variable, and you won't see NaN again.

Categories