Passing two dates to alert - javascript

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);

Related

How to format "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply mm.dd.yy using Google App Script>

I am trying to convert my date column from a google sheet from "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply 09.11.20. I tried this code but it does not convert and throws an error. Please advise:
var date1 = sheet.getRange('P2:P2').getValues(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yy");
What do I need to change here?
Try var date1 = sheet.getRange('P2').getValue()
getValues() returns a multidimensional array.
Since you want to get only cell P2 you should use
sheet.getRange('P2').getValue() instead.
assuming the latter returns a date object, this would probably work:
var date1 = sheet.getRange('P2').getValue(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy");
If the result you are getting is the day of yesterday, then try this:
var date1 = sheet.getRange('P2').getValue(); //my date field
var df = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy").split('.');
var date_formatted = `${df[0]}.${parseInt(df[1])+1}.${df[2]}`;

Get time from- new Date().getTime();

I am trying to get the time of device. The code I am using is like this -
const estimatedDeviceTimeMs = new Date().getTime();
alert(new Date(estimatedDeviceTimeMs));
The result of above code is Thu Jul 30 2020 12:01:54 GMT+0530 (India Standard Time).
I need to take out 12:01:54 in a variable and GMT+0530 in another variable if possible.
toTimeString return the time. Then split by space to get time and timezone like below:
var date = new Date();
console.log(date.toTimeString().split(" ")[0]);
console.log(date.toTimeString().split(" ")[1]);
Try this out
let date = new Date();
let time = date.toTimeString().split(' ')[0];
let gmt = date.toTimeString().split(' ')[1];
console.log(`Time is ${time} and GMT is ${gmt} `);
In Bangla if you need it
const parts = new Date().toLocaleTimeString('bn-in',{timeZoneName:'long'}).split(" ");
console.log(parts)
const estimatedDeviceTime = parts.slice(0,1) + " " +parts.slice(2)
console.log(estimatedDeviceTime)
You can call it by specific
const time = new Date();
console.log(`${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`);

Javascript get date from /Date(1518696376959)/

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

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.

Javascript:String to date fails

I want to convert a date, given as yyyy-mm-ddThh:mm:ss to a Javascript Date.
First attemp:
var str = "2013-10-31T18:15:30";
var date = new Date(str)
Returns Thu Oct 31 2013 18:15:30 GMT+0100 (CET).
Second attemp:
var str = "2013-10-31T18:15:30";
var str_parts = str.split("T");
var date_parts = str_parts[0].split("-");
var time_parts = str_parts[1].split(":");
var date = new Date(date_parts[0], date_parts[1], date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
Returns Sun Dec 01 2013 18:15:30 GMT+0100 (CET). Do I miss something? Shouldn't this also return Thu Oct 31 2013 18:15:30 GMT+0100 (CET)? Somehow, the date is incorrect, while the time fits.
The corresponding fiddle: http://jsfiddle.net/4CLAj/2/
In the Date constructor Date(year,month,day,hour,minute,second) the month is zero-based, i.e. January is zero.
So for the second attempt:
var date = new Date(date_parts[0], Number(date_parts[1]) - 1, date_parts[2], time_parts[0], time_parts[1], time_parts[2]);
See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf section 15.9.1.4

Categories