Date Object and UTC Method - javascript

Why is this returning the 31st instead of the 1st? As I understand it, the UTC method requires 3 parameters ( full year, month, day ), and the day parameter must be an integer between 1 - 31. Because getDate() returns with an integer between 0 and 31, I also suspected 0 would be a possibility.
firstDay = new Date(Date.UTC( 2011 , 7 , 1 )).getDate();
// returns 31 (last day of this month)
Let me clarify and say, this is not a special case. With the day parameter as 2, 3, or 4, this will return 1, 2, 3, and so on.

Your timezone offset is negative so like -4. So 7/1/2011 at 12:00AM minus 4 hours is 6/31/2011 8:00PM. Date.UTC takes additional parameters that you can use to pass hours, minutes, seconds, and milliseconds.
But really, if you don't want the timezone adjustment use new Date(year, month, day)
firstDay = new Date(2011 , 7 , 1).getDate(); // returns 1 (first day of this month)

I am at (GMT-0700) Pacific Time. Here are the results when I conduct the following:
new Date( 2011, 7, 1 );
// -> Mon Aug 01 2011 00:00:00 GMT-0700 (Pacific Daylight Time)
new Date( Date.UTC( 2011, 7, 1 ) );
// -> Sun Jul 31 2011 17:00:00 GMT-0700 (Pacific Daylight Time)
Notice that pulling the UTC time gives me the date/time in my current location, 7 hours prior to the date specified because I'm 7 hours behind Greenwich Mean Time.

This is what you're looking for:
new Date(Date.UTC(2011, 7, 1) + ((new Date).getTimezoneOffset() / 60) * 3600000).getDate();
Explanation:
(new Date).getTimeZoneOffset(); // will retrieve the timezone offset, (420 in my case PST)
offset / 60; // we divide by 60 so we can get the number of hours between UTC and me
(offset / 60) * 360000 // is 60 (seconds) * 60 (minutes) * 1000 (ms)
+ Date.UTC(2011, 7, 1) // will give us the correct Date always

Related

Add one Day at the Date change also the hour

I have issue with a date.
I have two date (start and end) and I need to build an array of all date between these two.
My script is something like:
while(currentData < nodeLastDate){
currentData.setDate(currentData.getDate() + 1);
console.log(currentData)
}
But at Sat Mar 30 2019 there is an error and the data change also the time.
if you run this simple script you can see it.
let test = new Date(2019, 2, 30, 2)
console.log(test)
test = test.setDate(test.getDate() + 1)
console.log(new Date(test))
this is the result:
Sat Mar 30 2019 02:00:00 GMT+0100 (Ora standard dell’Europa centrale)
index.js?c69d:385 Sun Mar 31 2019 03:00:00 GMT+0200 (Ora legale dell’Europa central)
Is this normal?
Date.getDate() gets the day of the month, so you lose any other information. If you want to add a day to a date, simply use Date.getTime() and add the number of milliseconds in a day:
let test = new Date(2019, 2, 30, 2)
console.log(test)
test = test.setDate(test.getTime() + (1440 * 60000))
console.log(new Date(test))
Date.getTime returns the number of milliseconds since an arbitrary date known as the epoch date, so adding the number of milliseconds in a day will add exactly one day to your date. (1440 * 60000 is the number of milliseconds in a day because there are 1440 minutes in a day and 60000 milliseconds in a minute)

Incorrect Javascript Day When Added?

I have a javascript function that takes in a number X and a date, and returns a new Date that is X number of days away:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date();
return new Date(newDate.setDate(theDate.getDate() + numDaysToAdd));
}
I pass it a day that is Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time) and a number 7, but the result I got was Thu Jun 09 2016 16:05:32 GMT-0700 (Pacific Daylight Time). Why is it giving me the correct date but wrong month?
The problem is that newDate is always created from the current date (new Date()). In other words, if this function is executed in June it will produce a date in June, then try to set a the day of the month as a offset from the input date.
You need to construct newDate as a copy of theDate:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date(theDate);
newDate.setDate(theDate.getDate() + numDaysToAdd);
return newDate;
}
var d = new Date('Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time)');
console.log(addDays(d, 7).toString());
You can add number of milliseconds to given date and it will generate correct date.
getTime() returns milliseconds from epoch.
offset = numDaysToAdd * 24 * 60 * 60 * 1000;
24: Hours in a day
60: Minutes in an hour
60: seconds in a minute
1000: milliseconds in a second
Date constructor takes milliseconds from epoch
function addDays(theDate, numDaysToAdd) {
var start = theDate.getTime();
var offset = numDaysToAdd * 24 * 60 * 60 * 1000;
return new Date(start + offset);
}
var today = new Date();
console.log(today, addDays(today, 10));

sethours updating time part but not the date part in date time field

I've a datetime field with date only as format. Also, I've added a script at onload so that whenever a record is accessed 12:00 should be added to that field. It works as expected and add 12 hours to the time part. But it do not update the date accordingly.
For example, I've Date Become Manager field and its value is 'Thu Apr 30 23:00:00 UTC-1200 1992'. And after adding 12 hours it updates the time part as 'Thu Apr 30 12:00:00 UTC-1200 1992' but do not add anything to its date. Following is my snippet for this to update.
function updateFields(field){
var dateField = Xrm.Page.getAttribute(field);
if(dateField.getValue()== null)
{
dateField.setValue(new Date());
}
dateField.setValue(dateField.getValue().setHours(12, 0, 0));
}
Please let me know if I am doing something wrong in it.
setHours only changes the time, it doesn't compute anything.
The most common way to perform this kind of computation is this:
var numberOfHours = 12; // how many hours you want to add. Can be *negative* too.
var millisecondsInAnHour = 60 * 60 * 1000; // this is constant
var offset = numberOfHours * millisecondsInAnHour;
var newFieldValue = dateField.getValue().getTime() + offset;
dateField.setValue(newFieldValue);
Basically, you grab the time of the value and add/subtract a number of milliseconds to it.
So to be clear, you want to add 12 hours to the current date value, (as opposed to just setting time element to 12:00)?
setHours just sets the time, it doesn't add 12 hours to the time. If you do it multiple times it will always be 12 hours, rather than 0 - 12 - 24.
If you combine setHours with getHours you should be able to achieve the desired behaviour.
var d1 = new Date();
console.log("Original Date: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Once: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Twice: " + d1);
var d2 = new Date();
console.log("Original Date 2: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Once: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Twice: " + d2);
Output:
Original Date: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Once: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Twice: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Original Date 2: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Once: Tue Sep 22 2015 21:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Twice: Wed Sep 23 2015 09:45:39 GMT+0100 (GMT Daylight Time)
I just updated my code and it works. Please have a look into following code snippet.
function updateFields(field){
var dateField = Xrm.Page.getAttribute(field);
if(dateField.getValue()== null)
{
dateField.setValue(new Date());
}
dateField.setValue(dateField.getValue().setHours(dateField.getValue().getHours() + 12));}

Moment.js - How To Detect Daylight Savings Time And Add One Day

I need to create Date Objects from strings of Date data for every hour of every day since the year 2000.
The strings look like this for every hour, in a Month/Day/Year Hour format...
"04/02/2000 01", "04/02/2000 02", "04/02/2000 03" ...all the way to... "04/02/2000 24"
Now, I have the following code, which works fine except for on days with Daylight Savings Time...
// Split At Space
var splitDate = "04/02/2000 24".split(/[ ]+/);
var hour = splitDate[1];
var day = splitDate[0];
// Split At Slashes
var dayArray = day.split("/");
if (hour === "24") {
// Months are zero-based, so subtract 1 from the month
date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], 0, 0, 0 ));
date.setDate(date.getDate() + 1);
} else {
// Months and Hours are zero-based, so subtract 1 from each
date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], hour, 0, 0 ));
};
On days with daylight savings time, like 04/02/2000 adding a day does not work if the hour is 24. Instead, it just returns Sun, 02 Apr 2000 23:00:00 GMT
With Moment.js, is it possible to detect a DST day and get this code to work correctly?
To detect DST, use the .isDST() method: http://momentjs.com/docs/#/query/is-daylight-saving-time/
moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST
Using this test, you should be able to determine how to modify your program's behavior accordingly.
Here's how I made a little checker:
var curDst = dtdate.isDST()
var prevDst = moment(dtdate).clone().subtract(1, "day").isDST();
var nextDst = moment(dtdate).clone().add(1, "day").isDST();
var isDstChangeDate = (curDst !== nextDst) === true || (curDst === prevDst) !== true;

Javascript date parsing bug - fails for dates in June (??)

I have some javascript which parses an ISO-8601 date. For some reason, it is failing for dates in June. But dates in July and May work fine, which doesn't make sense to me. I'm hoping a fresh set of eyes will help, because I can't see what I'm doing wrong here.
Function definition (with bug)
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
var date = new Date();
date.setUTCFullYear(parseInt(matches[1], 10));
date.setUTCMonth(parseInt(matches[2], 10) - 1); //UPDATE - this is wrong
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCMinutes(parseInt(matches[5], 10) - offset);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMilliseconds(0);
return date;
}
return null;
}
Test code
alert(parseISO8601('2009-05-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-06-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-07-09T12:30:00-00:00').toUTCString());
Output
Sat, 09 May 2009 12:30:00 GMT
Thu, 09 Jul 2009 12:30:00 GMT
Thu, 09 Jul 2009 12:30:00 GMT
Update
Thanks for the quick answers, the problem was that the Date object was initially today, which happened to be July 31. When the month was set to June, before I changed the day, it was temporarily June 31, which got rolled forward to July 1.
I've since found the following to be a cleaner implementation, as it sets all the date attributes at once:
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
return new Date(
Date.UTC(
parseInt(matches[1], 10),
parseInt(matches[2], 10) - 1,
parseInt(matches[3], 10),
parseInt(matches[4], 10),
parseInt(matches[5], 10),
parseInt(matches[6], 10)
) - offset*60*1000
);
}
return null;
}
The problem is that today is July 31.
When you set:
var date = new Date();
Then date.getUTCDate() is 31. When you set date.setUTCMonth(5) (for June), you are setting date to June 31. Because there is no June 31, the JavaScript Date object turns it into July 1. So immediately after setting calling date.setUTCMonth(5) if you alert(date.getUTCMonth()); it will be 6.
This isn't unique to June. Using your function on the 31st of any month for any other month that does not have 31 days will exhibit the same problem. Using your function on the 29th (non-leap years), 30th or 31st of any month for February would also return the wrong result.
Calling setUTC*() in such a way that any rollovers are overwritten by the correct value should fix this:
var date = new Date();
date.setUTCMilliseconds(0);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMinutes(parseInt(matches[5], 10) - offset);
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCMonth(parseInt(matches[2], 10) - 1);
date.setUTCFullYear(parseInt(matches[1], 10));
The date object starts off with the current date.
It's the 31st today so setting 2009-06-09 gives:
var date = new Date(); // Date is 2009-07-31
date.setUTCFullYear(2009); // Date is 2009-07-31
date.setUTCMonth(6 - 1); // Date is 2009-06-31 = 2009-07-01
date.setUTCDate(9); // Date is 2009-07-09
If you set the date to the 1st before you begin, then you should be safe.
It's because today is July 31. Grant explained the problem. Here's what I believe is a simpler solution. Initialize your date on Jan 1.
var date = new Date(2009,0,1,0,0,0);
It's the order in which you are changing the date.
The date starts out as July 31, so the set of the month fails because there is no 31 in June. (Actually it is rolling over to jul-1.)
After setting the full year, add this:
date.setYUTCDate(1);
It makes it the first of the month wherein every month is valid.
Looks like a bug?
C:\Documents and Settings\me>java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2009 03 22
js> date = new Date();
Fri Jul 31 2009 15:18:38 GMT-0400 (EDT)
js> date.setUTCMonth(5); date.toUTCString();
Wed, 01 Jul 2009 19:18:38 GMT
js> date.setUTCMonth(5); date.toUTCString();
Mon, 01 Jun 2009 19:18:38 GMT
EDIT: Nevermind I guess. Question already answered by somebody more knowledgable.

Categories