Javascript get date from /Date(1518696376959)/ - javascript

How to get date time from this /Date(1518696376959)/ in javascript?
I have tried like this
var d = new Date("1519192874994");

I have tried like this var d = new Date("1519192874994");
No need to wrap it in quotes, Date constructor will takes millisecond value (Number)
var d = new Date(1519192874994) //Wed Feb 21 2018 11:31:14 GMT+0530 (India Standard Time)
From "/Date(1518696376959)/"
Make it
var str = "/Date(1518696376959)/";
var date = new Date( +str.match(/\d+/g)[0] ); //notice the unary plus after getting the match

Related

Passing two dates to alert

In javascript, I'm running this:
var y2k = new Date(Date.UTC(2000,0));
var allFives = new Date(Date.UTC(2005,4,5,5,55,55));
alert(y2k, allFives);
I get Sat Jan 01 2000 00:00:00 GMT+0000 (GMT) from alert. I was expecting something like: Sat Jan 01 2000 00:00:00 GMT+0000 (GMT), Thu May 05 2005 05:55:55 GMT+0000 (GMT).
What happens when two dates are passed as arguments to alert?
alert() expects only one argument. alert(some expression) you can achieve your output by concatenating variables like -
var y2k = new Date(Date.UTC(2000,0));
var allFives = new Date(Date.UTC(2005,4,5,5,55,55));
alert(y2k + ", " + allFives);
https://developer.mozilla.org/en-US/docs/Web/API/Window/alert
alert() assumes this structure:
alert(some expression)
so you can either convert them to strings and then pass in alert
var y2k = new Date(Date.UTC(2000,0)).toString();
var allFives = new Date(Date.UTC(2005,4,5,5,55,55)).toString();
alert(`${y2k}, ${allFives}`);
Only one variable should be passed into alert function.
var y2k = new Date(Date.UTC(2000,0));
var allFives = new Date(Date.UTC(2005,4,5,5,55,55));
alert(y2k + ', ' + allFives);

Comparing two dates in different timezones

I'm comparing two dates; one returned as a UTC String (as part of an Ajax response) and the second in local browser time:
Basically, I want to see if the date returned (endTime) happened before right now. My code is below and I thought I had it right but it's not working.
var isActive = true;
var buffer = 30000; // 30 seconds
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
var nowUtc = new Date(now).toUTCString(); // "Fri, 23 Oct 2015 00:01:31 GMT"
var nowTimeMs = new Date(nowUtc).getTime(); // 1445558491000
var endTimeMs = endTime.getTime() + buffer; // 1445616104000
if( nowTimeMs > endTimeMs ){
isActive = false;
}
isActive should remain as true but instead it's false. I feel like I've been looking at this too long and am missing something very simple. Am I?
Thanks for any helpful tips.
Update:
Based on the responses I thought I'd update my question. What is the best way to compare two dates where one is this:
new Date(); // Thu Oct 22 2015 21:51:53 GMT-0400 (EDT)
...and the other is a String representation of date:
"2015-10-23 01:49:27"
I figure the best way to create a valid Date object out of the String is using this code.
isThisActive:function(p){
var isActive = true;
var buffer = 30000;
var pEndTime = myObj.parseStringAsDate(p.callEndTime);
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
now.setTime( now.getTime() + offset );
var nowTimeMs = now.getTime();
var endTimeMs = pEndTime.getTime() + buffer;
if( nowTimeMs > endTimeMs ){
isActive = false;
}
return isActive;
},
parseStringAsDate:function(str){
var dateTimeStr = str.split(" ");
var dateStr = dateTimeStr[0].split("-");
var year = dateStr[0];
var month = dateStr[1];
var day = dateStr[2];
var timeStr = dateTimeStr[1].split(":");
var hours = timeStr[0];
var minutes = timeStr[1];
var seconds = timeStr[2];
return new Date( year,month,day,hours,minutes,seconds);
}
Because "pEndTime" is in UTC I applied the offset to the "now" Date object but even this is not working. Where's the problem here? I thought this would solve it.
SOLVED:
The latest code I posted did work. I was just getting incorrect values for the response.endTime (It wasn't converted to correct military time). Thank you everyone for your input. I've tried to upgrade as many helpful responses as I could.
You should not use the Date constructor or Date.parse (which do the same thing) to parse date strings. Either write your own parse function (below) or use a well maintained library.
To parse the format in the OP, you can use:
// Parse Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
function parseMMMDY(s) {
var b = s.split(/\W/);
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var sign = /GMT-\d{4}/i.test(s)? 1 : -1;
var min = +b[5] + (sign * b[8].slice(0,2) * 60 ) + (sign * b[8].slice(-2));
return new Date(Date.UTC(b[3], months[b[1].toLowerCase().slice(0,3)], b[2], b[4], min, b[6]));
}
document.write(parseMMMDY('Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)'));
I think the problem is here:
var endTime = new Date(Date.parse(response.endTime));
respnonse.endTime is UTC, right? But when you parse it to Date value, Date.parse assumes it is in local timezone (GMT-0400 as in your example code). It means that the endDate gets the wrong value
I usually use moment.js in my projects which related to formatting date time, especially in the reports (I'm working in the field of finance). You must have one more library in your project but it provides many other functionalities
Sorry, this is for your new update. I haven't got enough 'population' to leave a comment :P
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
Your endTime doesn't seem to return a UTC date as you mentioned. It looks to be using (EDT) so maybe you didn't have to convert it to UTC.

converting date into timestamp

I have date like this 25. 02. 2014 18:48:21 and I'm trying to convert it into timestamp
var someDate = '25. 02. 2014 18:48:21';
var timestamp = new Date(someDate).getTime();
but it's returning NaN since I moved files to a new domain, what can be a problem?
'25. 02. 2014 18:48:21' is not a valid date format. You'll have to convert it with regex first, like that:
var someDate = '25. 02. 2014 18:48:21';
var converted = someDate.replace(/^(\d{2}\. )(\d{2}\. )(\d{4})/, '$3. $2$1');
// converted is in format: YYYY. MM. DD.
var timestamp = new Date(converted).getTime();
Running this within the console, creating a new date with that variable gives me Invalid Date. Trying switching around the 25. and 02. like so:
var someDate = '02. 25. 2014 18:48:21';
var timestamp = new Date(someDate).getTime(); // 1393372101000
The format should be "Month, Day, Year, Time".
Switching month and day will work. I also removed the dots.
var date = "25. 02. 2014 18:48:21";
new Date(date.replace(/(\d{2})\. (\d{2})\./, '$2 $1'))
// Tue Feb 25 2014 18:48:21 GMT+0100 (W. Europe Standard Time)
you can try something like below (if your string has always same format)
var someDate = '25. 02. 2014 18:48:21';
var arr = someDate.split(' ');
var time = arr[3].split(':');
var timeStamp = new Date(arr[2],arr[1].split('.')[0],arr[0].split('.')[0],time [0],time[1],time[2]).getTime();
It uses javascript date object constructor
var d = new Date(year, month, day, hour, minute, seconds);
which works across all browsers
function convertSomeDate(str){
var d= str.match(/\d+/g),
dA= [d[2], '-', d[1], '-', d[0], 'T', d[3], ':', d[4], ':', d[5], 'Z'].join('');
return +new Date(dA)
}
var someDate= '25. 02. 2014 18:48:21';
convertSomeDate(someDate)
/* returned value: (Number)
1393354101000
*/

Need clarity on javascript date logic

I am getting false for both conditions
localStorage.getitem("dl-visited-date") // "Mon Oct 07 2013 13:58:18 GMT-0400 (EDT)";
currentDate // Tue Oct 08 2013 14:18:26 GMT-0400 (EDT)
currentDate > localStorage.getItem("dl-visited-date") //false
currentDate < localStorage.getItem("dl-visited-date") //false
localStorage.getitem does return a string (your Date object was implicitly stringified when you stored it in the localstorage). If you compare this with a Date object, both will be casted to numbers, but while this works for the Date object the string will become NaN. And that compares false to anything.
You will need to parse it before (using the Date constructor):
var date = new Date(localStorage.getitem("dl-visited-date")),
currentDate = new Date();
If you want to test them for equality, you will need to use plain numbers instead. Use Date.parse then:
var dateStamp = Date.parse(localStorage.getitem("dl-visited-date")),
currentDateStamp = Date.now();
$(function () {
var dateformate = localStorage.getItem("selectedFormat");
alert(dateformate);
});

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Categories