Calculate Date with start date and number of days with javascript - 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.

Related

Javascript - Remove year and write full weekday name in date name

I'd like to use JavaScript to write the date TWO days from now. I'd prefer to show the full weekday name, and not show the year. For example, right now the code I have writes:
"Fri May 08 2020"
and I'd like it to say:
"Friday, May 08"
The script I have is:
<script>
var days = 2;
var newDate = new Date(Date.now() + days * 24*60*60*1000).toDateString();
document.write(newDate);
</script>
Thank you for your help!
Tim
You can do this easily by using Date.prototype.toLocaleString() or Date.prototype.toLocaleDateString() method and passing some parameter to the options object like:
var days = 2;
var newDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
.toLocaleDateString(undefined, { weekday: 'long',month: 'long',day: '2-digit' });
document.write(newDate);
//=> Friday, May 08
Few things here:
weekday: 'long' is used to display weekday in long-form like Friday instead of Fri.
day: '2-digit' is used to display date like 08 instead of 8.
You can see without passing these options date will be displayed like:
var days = 2;
var newDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toLocaleDateString();
document.write(newDate);
//=> 5/8/2020

javascript getting hour and min from epoch value

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

Javascript adding days to a Date

Hi I am trying to create a variable today that is the current date today. I am trying to add 106 days to it which works successfully. Then I am trying to create a second variable today2 and subtract 31 days from the 'today' variable (current date + 106 -31). This part is not working. This is what it is giving me...
Thu Mar 28 11:52:21 EDT 2013
Tue Nov 27 11:52:21 EST 2012
The second line is not 31 days before the first line. Can someone help me correct this?
Feel free to play with my jsfiddle http://jsfiddle.net/fjhxW/
<div id="current"></div>
<div id="current2"></div>
<div id="current3"></div>
var today = new Date();
var today2 = new Date();
today.setDate(today.getDate() + 106);
today2.setDate(today.getDate() - 31);
var dd = today.getDate();
var mm = today.getMonth(); //January is 0!
var yy = today.getFullYear();
document.getElementById('current').innerHTML = today;
document.getElementById('current2').innerHTML = today2;
it's Xmas time so I give the answer just to copy/paste:
var oneDay = 24 * 60 * 60 * 1000, // 24h
today = new Date().getTime(), // in ms
firstDate,
secondDate;
firstDate = new Date(today + 106 * oneDay);
secondDate = new Date(firstDate.getTime() - 31 * oneDay);
try datejs:
Date.parse('t - 31 d'); // today - 31 days
Date.today().add(106).days().add(-31).days();
You cannot pass a negative number to setDate. setDate is used to set the date to set the absolute day, not relative days.
From the docs:
If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly. For example, if you use 0 for dayValue, the date will be set to the last day of the previous month.
A mathemathical solution:
Add 75 days to your current day (106 - 31), then add 31 days to that date. Change the order in what you are showing both dates on your code.
Why go forward and backward when you can always go forward?

Need to display local times over DST transitions using Javascript Date Object

I am trying to output a series of times in hour (on the hour) intervals within Javascript (so inside a web browser such as Firefox). This series of times will overlap the short day (losing an hour in spring) and long day (gaining an hour in autumn). The output I'm looking for is in local time, i.e. with timezone and DST offsets applied. So for example, in the UK we have a missing hour from 01:00 to 01:59 on the short day such that the output would be:
00:00, 02:00, 03:00
And on the long day we have an extra hour from 01:00 to 02:00 such that the output would be:
00:00, 01:00, 01:00, 02:00, 03:00
I have already found these two brilliant answers that highlight some pitfalls and address part of my problem:
Daylight saving time and time zone best practices
Javascript Date objects and Daylight Savings Time
But the real difficulty is in making javascript aware of this missing and extra hour (so to speak) as identified in the second question mentioned above.
I think a potential solution to this would be to operate in UTC (aka GMT) and just do a conversion to local time but I'm struggling to see how I could do this.
Does anyone have any ideas about how to achive what I'm after?
If you have a fixed timezone, the following javascript code seems to work (tested on the last chrome version and firefox 6) :
// set the date to 11 / 04 / 2012 at 00:00 UTC
var date = new Date(1331424000000);
for(var i = 1; i <= 12; i++) {
$('.data-dston').append(' ' + date.getHours() + ':00, ');
date = new Date(date.getTime() + 3600000)
}
// set the date to 04 / 11 / 2012 at 00:00 UTC
var date = new Date(1351987200000);
for(var i = 1; i <= 12; i++) {
$('.data-dstoff').append(' ' + date.getHours() + ':00, ');
date = new Date(date.getTime() + 3600000)
}
Here's a JSFiddle : http://jsfiddle.net/Vsd2A/3/ to see the code in action !
Adapting what Krtek has come up with (for my timezone - UK) I now have the following:
// set the date to 27 / 03 / 2011 at 00:00 UTC
var date = new Date('27 Mar 2011 00:00');
for(var i = 1; i <= 12; i++)
{
$('.data-dston').append(' ' + date.getHours() + ':00, ');
date.setTime(date.getTime() + 3600000);
}
// set the date to 30 / 10 / 2011 at 00:00 UTC
var date = new Date('30 Oct 2011 00:00');
for(var i = 1; i <= 12; i++)
{
$('.data-dstoff').append(' ' + date.getHours() + ':00, ');
date.setTime(date.getTime() + 3600000)
}
Which has the benefit of not having to construct a new object on each iteration.

Javascript getDate problem

I have a very weird problem with javascript's getDate function. At the start of some function, i've created a Date object using:
var day = new Date(date);
in which date is a unix timestamp.
I dont change the day object, but after a while I try to get the day of the month of this object, but day.getDate() keeps giving me the wrong value.
For example:
alert(day.getTime() + "-" + day.getDate() + "-"+ day.getMonth() +"-" + day.getFullYear() + "-" + day.getHours() + "-" + day.getMinutes() + "-" + day.getSeconds());
gives me the following result: 1290297600-15-0-1970-23-24-57
and at some other point the result is: 1290384000-15-0-1970-23-26-24
And this is the weird part, if you lookup the unixtimestamp 1290297600 you'll see that that's the timestamp for the 21st of november 2010 at 00:00:00 gmt (1290384000 is the next day, same time)
The timestamps are correct, but i cant make sense of the dates it gives me.
This happens to me in any browser.
What am i doing wrong?
The issue here is that the Date object in JavaScript doesn't take the Unix timestamp (seconds since the epoch), it actually takes the milliseconds since the epoch. If you just multiply your date variable by 1000 then you get the correct output.
Example here
Time = Unix timestamp format. I added 64800 second to the time so it would be converted to Mountain Standard Time.
*timestamp 24 * 60 * 60
.getTime()//milliseconds 24 * 60 * 60 * 1000
private DateField dateField1; ///////////////////////
dateField1= new DateField("Date:", DateField.DATE); f.append(dateField1);
Date d = new Date(); dateField1.setDate(d);
String TimeSeg = String.valueOf(((dateField1.getDate().getTime()/1000)+64800));

Categories

Resources