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));
Related
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.
I'm trying to compute the date of the day before using:
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
It seems to work well when printed out using:
document.write(nda);
The output is:
Thu Nov 24 2016 00:00:00 GMT+0000 (WET)
which is correct, but when I do:
document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());
I get a wrong output:
2016-10-4
Any suggestion?
You need to do nda.getMonth() + 1.
Months start from 0 so in order to get the right number of the month you must add 1.
Also you need to use getDate() instead of getDay(). getDay will give you the day of the week, while getDate will give you the day of the month.
The end result would be:
nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
document.write((nda.getFullYear())+
"-"+(nda.getMonth()+1)+
"-"+(nda.getDate()));
Date.getMonth() returns the index of the month, which is 0-indexed (So 0 is January, and 11 is December). To correct for this, you add 1.
Date.getDay() returns the day of the week, which is also 0-indexed starting from Sunday (So 4 is Thursday).
Here, you would use Date.getDate() to get the day in the current month (Which is not 0-indexed).
var da = new Date('2016-11-25'),
nda = new Date(da-86400000);
document.write(nda.getFullYear() + "-" +
(nda.getMonth() + 1) + "-" +
nda.getDate());
There is a fundamental rule wiht parsing dates: do not use the Date constructor or Date.parse (they are equivalent for parsing) to parse date strings. Use a library with a parser or parse it yourself with a simple function.
When using:
var da = new Date('2016-11-25');
the date will be treated as UTC, so if you are in a timezone that is west of Greenwich the local date will be the day before. Note the differences in the following:
console.log('Built-in parse: ' + new Date('2016-11-25').toLocaleString());
console.log('No parse : ' + new Date(2016, 10, 25).toLocaleString());
When you do:
nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay();
as others have said, you should use nda.getMonth() + 1, and you want getDate rather than getDay. However, since you are parsing the date as UTC then getting local values, the previous issue with UTC may mean that the date is one day previous.
To construct a date in the local time zone and avoid parsing errors, set the values directly.
To get the day before any date, simply subtract one day. Don't subtract 24 hours or you'll then get errors over daylight saving boundaries (since those days aren't exactly 24 hours long). e.g.:
/* Format a date as yyyy-mm-dd
** #param {Date} date
** #returns {string}
*/
function formatDate(date) {
return date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
var nda = new Date(2016, 10, 25);
console.log('Created date: ' + formatDate(nda));
nda.setDate(nda.getDate() - 1);
console.log('Previous day: ' + formatDate(nda));
I have a nodejs application which is hosted in IST Timezone server. The application has a configuration to accept timezone from user (Pacific Daylight Time). So based on the user timezone I need to display data to him. But when I fetch timezone for particular user in server to retrieve some statistics data in server, even though proper timezone is fetched it still returns Date() relating to the server and not according to user preferred timezone. Below is the piece of code am following:
var offset=-8; //(Pacific Daylight Time)
var d = new Date( new Date().getTime() + offset * 3600 * 1000);
The above var d will still have server timezone captured and fetches data based on server timezone. How can I get the date relating to the client's timezone preference, in server?
If you have stored the user's preferred time zone offset in your server, then you can create a date and time for that time zone based on the current system time of any system.
The Date internal time value is UTC, so for any Date, you can adjust the time value by the offset, then use UTC methods to output the require values in the desired format and append the time zone.
However, it's very much simpler to always work in UTC and let the host system generate date values based on system settings.
/* Given a Date, return an ISO 8601 formatted date and time string
** for a particular time zone.
** #param {number} offset - offset in minutes +east, -west
** #param {Date} d - date to use, default is now
** #returns {string} ISO 8601 formatted string for supplied time zone offset
*/
function dateForTimezone(offset, d) {
// Copy date if supplied or use current
d = d? new Date(+d) : new Date();
// Use supplied offset or system
offset = offset || -d.getTimezoneOffset();
// Prepare offset values
var offSign = offset < 0? '-' : '+';
offset = Math.abs(offset);
var offHours = ('0' + (offset/60 | 0)).slice(-2);
var offMins = ('0' + (offset % 60)).slice(-2);
// Apply offset to d
d.setUTCMinutes(d.getUTCMinutes() - offset);
// Return formatted string
return d.getUTCFullYear() +
'-' + ('0' + (d.getUTCMonth()+1)).slice(-2) +
'-' + ('0' + d.getUTCDate()).slice(-2) +
'T' + ('0' + d.getUTCHours()).slice(-2) +
':' + ('0' + d.getUTCMinutes()).slice(-2) +
':' + ('0' + d.getUTCSeconds()).slice(-2) +
'.' + ('000' + d.getUTCMilliseconds()).slice(-3) +
offSign + offHours + ':' + offMins;
}
document.write('Current date and time in US Pacific Daylight Time (PDT) time zone UTC-07:00 is: <br>' +
dateForTimezone(-420,new Date()));
In you server-side code var d = new Date( new Date().getTime() + offset * 3600 * 1000); time always returned server time instead of client's timezone, because it execute on server. So you can sent client's time as string in http request and then convert time string into actual time. Then you will get client's timezone time. Hope your problem will be solved.
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.
The use case is that I am getting the date in millis (from epoch) through an ajax call, which now needs to be interpreted in the javascript. This corresponded to some point of time in UTC.
Now I need to display this date in PST, as that is the only relevant time zone for the users irrespective of where they are opening the page from.
Also, I need to show it in a different format like 'yyyy-mm-dd HH:mm' rather than the default Locale string.
Can someone please tell me, how I can do that.
Create a new date using the UNIX milliseconds value plus the offset to PST, then create your formatted string using getUTC series of calls.
Moment.js is a pretty nice library for this type of thing.
I believe the timezones are determined by the user's timezone setting when you use the new Date() function.
var myDateTime = 1312312732923;
var myDate = new Date(myDateTime);
var myFormattedDate = myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDay();
http://www.w3schools.com/jsref/jsref_obj_date.asp
JavaScript has now way to set the timezone that you want to display something in. I've used Flot for a library for charting and their suggested solution is to use the getUTC methods when displaying the dates. That means that your server code can't send the standard millis from epoch (since that would display GMT time), but a small adjustment on the server will make your dates display correctly on the client.
To read about the problem, see http://flot.googlecode.com/svn/trunk/API.txt, and look for the heading "Time series data"
Use the Date object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Javascript's Date object works with milliseconds rather than seconds, so you'll have to multiply a UNIX timestamp by 1000:
var myDate = new Date(unix_timestamp * 1000);
Then, you can use the local-specific Date object to do whatever you'd like:
var output = myDate .getHours() + ':';
output += myDate .getMinutes() + ':';
output += myDate .getSeconds();
alert(output);
EDIT Ah, missed the part about using PST always, regardless of locale. unix_timesamp again is the epoch/UNIX timestamp you're getting from the server:
Try it here: http://jsfiddle.net/46PYZ/
// set to the UTC offset for the target timezone, PST = UTC - 8
var target_offset = -8;
// create a Date object
var myDate = new Date();
// add local time zone offset to get UTC time in msec
var utc_milliseconds = (unix_timesamp * 1000) + (myDate .getTimezoneOffset() * 60000);
// set the time using the calculated UTC timestamp
myDate.setTime(utc_milliseconds + (3600000 * target_offset));
// now build the yyyy-mm-dd HH:mm format
var output = myDate.getFullYear() + '-';
var month = myDate.getMonth() + 1;
output += (month < 10 ? '0' + month : month) + '-';
output += myDate.getDate() + ' ';
var hours = myDate.getHours() + 1;
output += (hours < 10 ? '0' + hours : hours) + ':';
var minutes= myDate.getMinutes() + 1;
output += (minutes< 10 ? '0' + minutes : minutes);