I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;
Related
I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts).
I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked.
I'm pretty sure it should be a minor change but I cannot figure out how to solve this.
A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));
Your issue is that today is not a Date object, because you've called Utilities.formatDate on it. This is why you are getting an error when trying to use today.setDate(). So you need to use another variable to allow you to compute yesterday. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1) sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate) and subtract 1 from that to get yesterday's date.
getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},
function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object
Suppose I have a start date which is 3/Sep/2019 and end date 10/Sep/2019.
I want to get the date after 4 days from the starting date. So if my starting date is 3/sep/2019 I want to get 7/Sep/2019 but not 12/sep/2019 since this date comes after my end date.
How can I achieve this?
So far I'm getting dates after n number of dates like this:
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
date = new Date(res);
alert(date);
var days = 7;
var date = new Date();
var res = date.setDate(date.getDate() + days);
This is how you get a day 7 days after the date you already have. It wraps to the next month when appropriate as well.
Try the function I wrote below:
function getFutureDate(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
return date
}
const fourDays = getFutureDate(4)
console.log(fourDays)
Currently i'm facing the following problem. In my JavaScript code, i have a function, which should calculate the weeks from now, to a given timestamp. The problem is, that the the first value has the same Value as another variable with another name. The code:
let myAppointment = event.data.toTime;
console.log(myAppointment);
let currentDate = new Date(Date.now());
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
let appointmentStartDate = new Date(myAppointment.getStart());
console.log(appointmentStartDate);
console.log(currentDate);
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
console.log('AppointmentStartTime : ' + appointmentStartTime);
console.log('CurrentTime: ' + currentTime);
let timeskip = appointmentStartTime - currentTime;
console.log(timeskip + ' timeskip / 604800000 = ' + (timeskip / 604800000));
skips = timeskip / 604800000;
await displayCalendar(document.getElementById('wrapper'));
console.log(skips);
if(skips < 0){
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateBackward(skips);
}
}else{
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateForward(skips);
}
}
cleanTable();
displayAppointments();
});
//i think this function may be interesting too, but the error can't occur from here
function
convertStringDateToDate(year,month,day,hours,minutes,seconds,milliseconds){
let date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
return date;
}
The function from let myAppointment = ... Leads to the following console output
The problem lies here:
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
You set the hours, minutes, seconds all to zero - effectively turning your start date to the same value as today's date.
Note that in your particular example, currentDate and appointmentStartDate share the same year, month, and date. When you call let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
, you should replace 0,0,0,0 with correct values for both currentTime and appointStartTime.
To make your coding style consistent, you can use date.getHours(), date.getMinutes(), date.getSeconds(), and date.getMilliseconds() to replace those four zeroes.
Also, if you want to shorten your code, you can get rid of convertStringDateToDate() and merely call getTime() on currentDate and appointStartDate.
let currentDate = new Date();
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds())).getTime();
console.log(currentTime); // 1537309553647
console.log(currentDate.getTime()); // 1537309553647
I wrote a simple javascript function which converts string to date (in format 'dd.MM.yyyy HH.mm').
For extracting parts of that string, I've used slice method.
What is strange to me is that only day is returned as expected. All other variables are simply empty strings.
What am I doing wrong?
(
function(){
alert(GetDateFromStringDateTime("20.04.2017 18:15"));
}
)();
function GetDateFromStringDateTime(dateStr){
var day = dateStr.slice(0,2);
var month = dateStr.slice(3,2);
var year = dateStr.slice(6,4);
var hour = dateStr.slice(11,2);
var minute = dateStr.slice(14,2);
return new Date(year,month,day,hour,minute);
}
Picture from console window (month, year, hour and minute are empty strings):
String#slice() use a start and end parameter which are both zero-based index
console.log(GetDateFromStringDateTime("20.04.2017 18:15"));
function GetDateFromStringDateTime(dateStr) {
var day = dateStr.slice(0, 2);
var month = dateStr.slice(3, 5);
var year = dateStr.slice(6, 10);
var hour = dateStr.slice(11, 13);
var minute = dateStr.slice(14, 16);
console.log(day);
console.log(month);
console.log(year);
console.log(hour);
console.log(minute);
return new Date(year, month, day, hour, minute);
}
Use String.prototype.substr instead of slice
I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.