javascript getting hour and min from epoch value - javascript

i am using the below code to get the hh:mm from epoch
var dt = new Date(t*1000);
var hr = dt.getHours();
var m = "0" + dt.getMinutes();
return hr+ ':' + m.substr(-2)
for below values:
1542895249079 prints: 19:37 Expected: 2:00 PM
1542897015049 prints: 6:10 Expected: 2:30 PM
1542902445344 prints: 2:35 Expected: 4:00 PM
I am sort of lost on this as the conversion values from above code looks totally weird to me.

Two problems with your code:
For the example values you specified, there's no need to multiply by 1000 as they're already expressed in milliseconds.
If you want to leave local timezone information out of account, you have to use getUTCHours() and getUTCMinutes().
function convert(t) {
const dt = new Date(t);
const hr = dt.getUTCHours();
const m = "0" + dt.getUTCMinutes();
return hr + ':' + m.substr(-2)
}
console.log(convert(1542895249079));
console.log(convert(1542897015049));
console.log(convert(1542902445344));

Not what you need, but someone is useful to get a really quick approximation.
I use to process large amounts of intervals. Conversions would be painful.
Example: The epoch time 1621271327 as Monday, 17 May 2021 17:08:47 GMT
1621271327 % 86400 / 3600 => 17.14 // hours
1621271327 % 3600 / 60 => 8.78 // minutes
1621271327 % 60 => 47 // seconds

Related

Javascript function to calculate the hours remaining to specific date or time

I need to count the remaining time in hours between today or actual date/time and a specific end date at 00:00 hrs.
I tried in this fiddle, but I get the counting of one month more than it should be.
https://jsfiddle.net/alonsoct/52ts89mz/
var endTime = new Date(2019,10,18,0,0,0) / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalTime = endTime - elapsed;
var hr = parseInt(totalTime / 3600)
var min = parseInt(totalTime / 60) % 60;
var sec = parseInt(totalTime % 60, 10);
var result = hr + " hours, " + min + " minutes " + sec + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
If I enter one month less in the "endTime" variable I get the correct result in hours count, but this is not fine I need to enter the real end date without the need to subtract one month.
Thanks
The code below is mostly your code with one change. I changed the input for endTime to an ISO format and omitted the time Zone. This, in theory, will default to your browser's timezone. I tested on your linked and it worked. Here is some additional information https://www.w3schools.com/js/js_date_formats.asp
var endTime = new Date("2019-10-18T00:00:00") / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalSec = endTime - elapsed;
var h = parseInt( totalSec / 3600 )
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = h + " hours, " + m + " minutes " + s + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
Here is a working solution with Vanilla JS:
var calcTime = setInterval(function(){
date_future = new Date(2019,10,18,0,0,0)
date_now = new Date();
seconds = Math.floor((date_future - (date_now))/1000);
minutes = Math.floor(seconds/60);
hours = Math.floor(minutes/60);
days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
It's pretty easier with JQuery → http://hilios.github.io/jQuery.countdown/examples/show-total-hours.html
JavaScript counts months from 0 to 11.
January is 0. December is 11.
I think you were thinking that endTime will be October 18th, 2019 but actually it's November 18th, 2019.
You can see more relevant information here.
https://www.w3schools.com/js/js_dates.asp
Thanks.
If between the start-datetime and end-datetime a change takes place in winter / summertime remember to make summertime/wintertime adjustments
(if you get these values from e.g. an api:) if the startdate is specified by a client in location x and enddate is specified in location y, you have take into account that the startdate could potentially be in 00:00:00+14:00 timezone and end the endate in max -14 timezone.
if you only present 2 timeboxes: time 1 and time 2, you can map these anywhere on a 52 hours time-scale: -14 , +14 and the 24 hours gmt timescale where you then would normalize to. ( 0:00 could mean i am in Samoa +14, 14 hours ahead of the end of GMT 23:59:59 (14 further) or ahead of GMT 0:00 (14+24 further). Then there are countries which make local time decisions e.g. in India with +5.5 UTC or Burma +6.5 or newfoundland -3.5.
Since this is stackexchange and people will copy and paste these examples in their applications even if these applications are "on the internet" and so DO have users from every location in the world.
Therefore ... use a library: https://momentjs.com/ ; Get hours difference between two dates in Moment Js they have a helper https://momentjs.com/docs/#/displaying/to/ and see also: Moment.js - How To Detect Daylight Savings Time And Add One Day
You can see the same bug on https://www.timeanddate.com/countdown but they added in words : https://www.timeanddate.com/countdown/one-hour-offwintertijd (and they assume the end datetime is in the same location as the countdown datetime)

Timestamp calculated from the current time instead the source date

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

Get the time elapsed between two timestamps and convert it to date [duplicate]

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.
Example:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
//expected result:
"00:39:30"
what I tried:
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");
console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.
The result of moment.duration(now.diff(then)) is a duration with the correct internal values:
days: 0
hours: 0
milliseconds: 0
minutes: 39
months: 0
seconds: 30
years: 0
So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
but i feel that there is something more elegant that I am completely missing.
update
looking closer, in the above example now is:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
and moment(moment.duration(now.diff(then))) is:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(
update 2
well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.
This approach will work ONLY when the total duration is less than 24 hours:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.
This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
It doesn't give you exactly the format you're looking for, but
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1
Worked for me
See more in
http://momentjs.com/docs/#/displaying/difference/
If you want difference of two timestamp into total days,hours and minutes only, not in months and years .
var now = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));
diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:
var days = parseInt(diff.asDays()); //84
var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
hours = hours - days*24; // 23 hours
var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
minutes = minutes - (days*24*60 + hours*60); //20 minutes.
Final result will be : 84 days, 23 hours, 20 minutes.
When you call diff, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.
This should work fine.
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Use this:
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
Instead of
Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
It's better to do
moment.utc(total.asMilliseconds()).format("HH:mm:ss");
This will work for any date in the format YYYY-MM-DD HH:mm:ss
const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();
const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
console.log(duration.asHours());
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
DATE TIME BASED INPUT
var dt1 = new Date("2019-1-8 11:19:16");
var dt2 = new Date("2019-1-8 11:24:16");
var diff =(dt2.getTime() - dt1.getTime()) ;
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var response = {
status : 200,
Hour : hours,
Mins : mins
}
OUTPUT
{
"status": 200,
"Hour": 0,
"Mins": 5
}
The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');
// Getting the difference: hours (h), minutes (m) and seconds (s)
let h = end.diff(start, 'hours');
let m = end.diff(start, 'minutes') - (60 * h);
let s = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);
// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);
console.log(`${hh}:${mm}:${ss}`); // 00:39:30
This will return biggest time period diff like (4 seconds, 2 minutes, 1 hours, 2 days, 3 weeks, 4 months, 5 years).
I use this for notification recent time.
function dateDiff(startDate, endDate) {
let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
let index = 6 - dateMap.filter(e => e == 0).length;
return {
type: arrDate[index] ?? "seconds",
value: dateMap[index] ?? 0
};
}
Example:
dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")
{type: "hours", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")
{type: "days", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")
{type: "seconds", value: 10}
I create a simple function with typescript
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);
function setDiffTimeString(diffDuration: moment.Duration) {
const str = [];
diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
console.log(str.join(', '));
}
// output: 1 day(s), 23 hour(s), 29 minute(s)
for generate javascript https://www.typescriptlang.org/play/index.html
InTime=06:38,Outtime=15:40
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
EPOCH TIME DIFFERENCE USING MOMENTJS:
To Get Difference between two epoch times:
Syntax:
moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()
Difference in Hours:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()
Difference in minutes:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()
Note: You could remove .toFixed() if you need precise values.
Code:
const moment = require('moment')
console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')
Refer working example here:
https://repl.it/repls/MoccasinDearDimension
To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is
const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()
you can change the difference format as you need by just replacing the asMinutes() function
If you want a localized number of days between two dates (startDate, endDate):
var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
nbDaysStr will contain something like '3 days';
See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.
It is very simple with moment
below code will return diffrence in hour from current time:
moment().diff('2021-02-17T14:03:55.811000Z', "h")
const getRemainingTime = (t2) => {
const t1 = new Date().getTime();
let ts = (t1-t2.getTime()) / 1000;
var d = Math.floor(ts / (3600*24));
var h = Math.floor(ts % (3600*24) / 3600);
var m = Math.floor(ts % 3600 / 60);
var s = Math.floor(ts % 60);
console.log(d, h, m, s)
}

How do I get the number of days for a duration where the number of hours exceeds 24 in google sheets?

I am using google sheets where there is a duration value of 69:41:00 where it's 69 hours, 41 minutes, 0 secs. There doesn't seem to be a function to convert this to days, hours and minutes so I did some searching and some had suggested a custom function. Not sure exactly how it works but made some changes from the original to fit what I needed. The code below:
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Retrieve the hours and minutes
var hrs = duration.getHours();
var days = Math.floor(hrs/24);
var hours = hrs % 24;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
The result should be 2d 21h 44 min but instead I got 0d 21 h 35 min. Am I doing something wrong here?
I was going to add, why don't you just use a custom format of
ʺd\d hh\h mm\mʺ ?
This works fine in Excel but not in GS because it uses a different base for dates so duration like 69:41:00 would be interpreted as 1/1/1900 21:41 and the days are not correct. So you would have to break it down into days (whole numbers) and hours+minutes (fractions of a day) like this
=text(int(A1),ʺ#0\d ʺ)&text(mod(A1,1),ʺHH\h MM\mʺ)
You can make it work in Google Scripts if you want to by adjusting the date - should work OK for durations up to 1 month.
The reason for adding 2 to the date is that a time like 03:21:00 (less than a day) is seen as a date - namely 30th December 1899 ! So I add 2 to it to make it 1st January 1900. However, now the day part of the date is 1 and I want it to be zero. So I have to subtract 1 from the day further down.
This strange behaviour is probably why you're advised to do it the other way and work in milliseconds, but I was just interested to see if there was a way of making the original code work.
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Add 2 days to the date
var date=new Date(duration.setDate(duration.getDate()+2));
Logger.log(date.getDate());
var hours = duration.getHours();
// Take 1 off the day part of the date
var days = date.getDate()-1;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
function(durations){
var timeArr = durations.split(':'); //["69","41","00"]
//your code
}
getHours is a method of object Date.
var t = new Date;
t.getHours();
How do you expect to get more than 24hours from a Date object? It is not the same as what you expect as Duration. Date is for points of time in calendar, so at most you'd get the 23:59:59 of any day. You can get date2 - date1 = milliseconds diff, and work on it, as following;
function FormatDuration(date1, date2) {
var milliseconds = date2 - date1;
var mins = Math.floor((milliseconds / (1000*60)) % 60);
var hours = Math.floor((milliseconds / (1000*60*60)) % 24);
var days = Math.floor(milliseconds / (1000*60*60*24));
var result = days + ' d ' + hours + ' h '+ mins + ' min';
console.log(result);
}
FormatDuration(new Date(2000, 5, 1, 5, 13, 0, 0),
new Date(2000, 5, 2, 15, 31, 0, 0))
You can find more details here

Calculate Date with start date and number of days with javascript

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange results, but only on one date, I have been a few days now trying to figure this one out.
The function is:
CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var policy_start_date_add = new Date(policy_start_date.getTime() + ((days-1) * 24 * 60 * 60 * 1000));
var dateString = ("0" + (policy_start_date_add.getDate())).slice(-2) + "-" + ("0" + (policy_start_date_add.getMonth()+1)).slice(-2) + "-" + policy_start_date_add.getFullYear();
return dateString;}
The thing is it works until I use the date "28-10-2012" it gives me back the same date even if I add 2 days.
Any ideas, I am stumped.
Likely your local timezone changes because of the end of the daylight saving time.
> new Date(2012, 9, 28)
Sun Oct 28 2012 00:00:00 GMT+0200
> // 48 hours later:
> new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
Mon Oct 29 2012 23:00:00 GMT+0100
Always use the UTC methods!
BTW, adding days is much more easier with setDate, which also works around timezone issues:
function calculateDateFromDays(startDate, days) {
var datestrings = startDate.split("-"),
date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
date.setDate(date.getDate() + days);
return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
}
On October 28th the time changes from DST to "normal", so the day is not equal 24h. That may cause issues in your code.
Also why (days-1) * 24 * 60 * 60 * 1000? If you set days to 1 the whole expression evaluates to zero...
There's an easier way to achieve that :
http://jsfiddle.net/pjambet/wZEFe/2/
Use javascript date format:
How to format a JavaScript date
So you don't have to manually try to parse date strings.

Categories

Resources