Compare time only when time zone changed in 1920 - javascript

I have a time value of "7:00:00 AM" in my spreadsheet. Hypothetically, I want to compare this to another hour/minute time value (date agnostic) in my Google Apps Script code. When the script reads the value, because no date was attached, it assumes a date of 30-Dec-1899. Now, the issue is, because the time zone where I currently am was GMT+06:42:04 back in 1899, the time value appears as "07:17:56".
How can I compare this time with another to know if the hours and minutes match? This would ideally be done with vanilla JS (i.e. I prefer not to use Moment.js).
function getCellValue() {
var cellValue = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
Logger.log(cellValue); // Sat Dec 30 07:00:00 GMT+06:42 1899
Logger.log(cellValue.getHours()); // 7.0
Logger.log(cellValue.getMinutes()); // 17.0
Logger.log("Untouched: " + cellValue); // Untouched: Sat Dec 30 1899 07:17:56 GMT+0700 (ICT)
var formattedTime = Utilities.formatDate(cellValue, "GMT+7", "EEE MMM dd yyyy HH:mm z");
Logger.log("Formatted: " + formattedTime); // Formatted: Sat Dec 30 1899 07:17 GMT+07:00
var updatedCellValue = new Date(cellValue.setFullYear(2018));
Logger.log("New Year: " + updatedCellValue); // New Year: Sun Dec 30 2018 07:17:56 GMT+0700 (ICT)
var updatedDate = new Date(cellValue);
Logger.log("Converted: " + updatedDate); // Converted: Sat Dec 30 1899 07:17:56 GMT+0700 (ICT)
Logger.log("Converted & formatted: " + Utilities.formatDate(updatedDate, "GMT+7", "EEE MMM dd yyyy HH:mm z")); // Converted & formatted: Sat Dec 30 1899 07:17 GMT+07:00
}
Both my spreadsheet and script are set to "(GMT+07:00) Bangkok" time zone.
(I understand that 7am today and 7am in 1899 were not the same, but that is irrelevant to this hypothetical. If a user enters 7am in the spreadsheet, they probably mean that to be 7am this century.)

getDisplayValue(), not getValue()
Create a new Date object from value
Use Utilities.formatDate() to get the hour & minutes
Fixed code:
function getCellValue() {
var cellValue = SpreadsheetApp.getActiveSheet().getRange("A1").getDisplayValue();
Logger.log(cellValue); // 7:00:00 AM (or 0.29, if formatted as number)
cellValue = new Date(cellValue);
var hours = Utilities.formatDate(cellValue, "GMT+7", "HH");
var minutes = Utilities.formatDate(cellValue, "GMT+7", "mm");
Logger.log (hours + ":" + minutes); // 07:00
}

Related

Javascript Converting Ints to Time?

For a project app I'm making, a homework keeper, I need to be able to turn a number like 10 into a month like october, then do this with year, month, day, and time. Then I need to save it all in a date. How do I do this? I have been looking everywhere and cannot find how to do it.
It looks like you're looking for the Date() constructor.
var month = 10;
var day = 17;
var year = 2017;
var hour = 8;//Use the 24 hour clock for times in the PM
var minutes = 36;
var date = new Date(year, month-1, day, hour, minutes);//Outputs October 17th, 2017 at 8:36am in your local timezone
You have to subtract 1 from the month because January starts at 0, not 1.
Alternatively, I like to use moment.js for the flexibility depending on use, so you could instantiate it like this:
var date = moment(year + '-' + month + '-' + day + ' ' + hour + ':' + minutes, 'YYYY-M-D H:m');//Because you are using numbers/integers, none of them will have preceding zeroes
Take a look at the Date constructor - I think it doesn everything you need.
Your biggest gotcha is that months are 0-indexed so you'll actually turn 9 into October. Also beware that if you don't initialise Date with anything, it'll assume you mean now.
var date = new Date();
date; // -> Tue Oct 17 2017 13:34:49 GMT+0100 (GMT Daylight Time)
date.setMonth(10); // -> 1510925689970
date; // -> Fri Nov 17 2017 13:34:49 GMT+0000 (GMT Standard Time)

How to get total minutes of difference between two dates using pure JavaScript

Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!

javascript getTime() returns greater value for older date compared to new date

javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.

Javascript Date add days

var date = new Date();
var date2 = new Date();
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);
Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60
If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.
Any help please?
Convert the value to a number first, e.g. with the unary plus operator:
var daysinadvance = +document.getElementById('AdvanceDays').value;
// ^ unary plus
Otherwise daysinadvance will be a string and you are doing string concatenation.

Adding 30 minutes to Date causes it to go back 30 minutes

I have a Javascript Date object equal to 00:30 and when doing:
date.setMinutes(date.getMinutes() + 30);
causes the date object to equal 00:00.
Does anyone know why this is happening?
Here is where the code is being used:
for (var i = openTime; i <= closeTime; i.setMinutes(i.getMinutes() + timeIncrement)) {
var time = i.getHours() + (i.getHours() == 0 ? '0' : '') + ':' + i.getMinutes() + (i.getMinutes() == 3 || i.getMinutes() == 0 ? '0' : '');
$(timeClientId).append($('<option />').val(time).text(time));
}
The above script creates a list of times available from 10:00am all the way to 02:00am the next day.
It runs fine until it reaches midnight 00:00 after many successful iterations.
Can anyone help?
Thanks!
ANSWER/SOLUTION:
This problem was due to a daylight saving issue, so this Saturday the clocks go forward. For some odd reason when adding 30 minutes to 12:30 it reset back to 12:00 using .setMinutes(). This kept it in an endless loop.
The solution was to add minutes using
i.setTime(i.getTime() + timeIncrement * 60 * 1000)
This sorted the issue.
Cheers for all your answers!
You are only setting the minutes. So of course 30 minutes + 30 minutes on the clock equals 60 minutes, i.e. 0 minutes.
Use this clever method (it's clever because it works with all rollovers!):
function addMinutes(inDate, inMinutes)
{
var newdate = new Date();
newdate.setTime(inDate.getTime() + inMinutes * 60000);
return newdate;
}
var date = new Date();
alert(addMinutes(date,-30));​
How are you initialising your date? setMinutes seems to work as expected so perhaps there is an error in your initial value. See below for my quick n dirty test.
var date = new Date(0);
document.write(date);
document.write("<br>");
date.setMinutes(30);
document.write(date);
document.write("<br>");
date.setMinutes(date.getMinutes() + 30);
document.write(date);
document.write("<br>");
Outputs:
Thu Jan 1 00:00:00 UTC 1970
Thu Jan 1 00:30:00 UTC 1970
Thu Jan 1 01:00:00 UTC 1970
date.js has a good way to do this:
new Date().add({ minutes: 30 });
or even more fluid:
new Date().add(30).minutes();
try this:
var date = new Date(2013,2,31,1,59);
document.write(date,"<br>");
date.setMinutes(date.getMinutes()+30);
document.write(date,"<br>");
date.setMinutes(date.getMinutes() + 30);
document.write(date,"<br>");
date.setMinutes(date.getMinutes() + 30);
document.write(date,"<br>");
Sun Mar 31 2013 01:59:00 GMT+0100 (CET)
Sun Mar 31 2013 01:29:00 GMT+0100 (CET)
Sun Mar 31 2013 01:59:00 GMT+0100 (CET)
Sun Mar 31 2013 01:29:00 GMT+0100 (CET)
So obviously the switch to summer time in Germany is causing this result.
But was this intended?
Entering 2013,2,31,2,59 gives same result, as if the hour 1-2 did not exist.
it does not look right to me.

Categories

Resources