Time changes after toLocaleTimeString() - javascript

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.

Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

Related

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month

I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){
var lastRow = outputSheet.getLastRow();
var newDate = new Date();
var lastDate = outputSheet.getRange(lastRow,1).getValue();
var newDateRng = outputSheet.getRange(lastRow+1,1);
Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
newDate.setDate(lastDate.getDate());
Logger.log(newDate);
newDate.setDate((newDate.getDate() + 1));
Logger.log(newDate);
var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
Logger.log(newDateFormatted);
newDateRng.setValue(newDateFormatted);
}
With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks
You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var date = new Date(lastDate); // create new date object
var result = [];
for (var i=0;i<365;i++){
date=new Date(date).setDate(new Date(date).getDate()+1)
Logger.log('date='+new Date(date))
result.push([new Date(date)]);
}
SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}

How to get the difference in miliseconds between two Timestamps which are of different timezone in Javascript

i wanted to get the difference of two timestamps of different timezone in javascript:
var firstTime ="2017-07-21 04:34:21";
var timeZone1:"+0100";
var secondTime ="2017-07-21 04:36:27";
var timeZone2:"+0124";
How we can get the difference in miliseconds ?
Convert your strings into ISO 8601 formats. These generally work well in JavaScript Date constructors. Then simply subtract one from the other
var firstTime ="2017-07-21T04:34:21";
var timeZone1 = "+01:00";
var secondTime = "2017-07-21T04:36:27";
var timeZone2 = "+01:24";
const firstDate = new Date(firstTime + timeZone1)
const secondDate = new Date(secondTime + timeZone2)
console.log('firstDate', firstDate)
console.log('secondDate', secondDate)
console.info('diff', firstDate - secondDate)
you can use moment.js (https://momentjs.com/) for get the current timestamp from different time zone.
But donĀ“t forget : "Time Zone != Offset"
https://stackoverflow.com/tags/timezone/info
Another good example:
Get timezone difference in hours with moment

Save date 'without' time in JavaScript

At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?
An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );
Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);
Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);
To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function

difference between date with and without time portion

let's say that I have two variables: one that contains a date string (without time) and another one that contains the same date string but with time 00:00:00 like this:
var date1 = '2013-10-23';
var date2 = '2013-10-23 00:00:00';
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime()
console.debug('Date 1 time: ' + date1_time + "\n" + 'Date 2 time: ' + date2_time);
The result in the console is this:
Date 1 time: 1382486400000
Date 2 time: 1382500800000
Why aren't these two equal to the same thing? Shouldn't date1's time portion default to 00:00:00 since I did not put a time?
Thank you
I just tested it on chrome and found out that
The first one gives you the timestamp for 00:00:00 UTC
The second gives you timestamp with your current timezone.
So if you substract them you will see +-your timezone:
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime();
console.log((date2_time-date1_time)/1000/60/60); //will print the timezone difference.
You can get exact what time the first variable is considering.
var timestamp = 1382486400000;
var date = new Date();
date = new date(timestamp + date.getTimezoneOffset() * 60000)
alert(date);
It all happens because of default UTC time zone and your current
timezone.

Categories

Resources