getMonth getUTCMonth difference result - javascript

I found and inconsistent result when using the JavaScript date.getMonth() and date.getUTCMonth(), but only with some dates. The following example demonstrates the problem:
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<p id="demo">Click the button to display the month</p>
<script type="text/javascript">
function myFunction()
{
var d = new Date(2012, 8, 1);
var x = document.getElementById("demo");
x.innerHTML=d;
x.innerHTML+='<br/>result: ' + d.getMonth();
x.innerHTML+='<br/>result UTC: ' + d.getUTCMonth();
}
</script>
</body>
</html>
The output of this example is:
Sat Sep 01 2012 00:00:00 GMT+0100 (Hora de Verão de GMT)
result: 8
result UTC: 7
If i change the date to (2012, 2, 1) the output is:
Thu Mar 01 2012 00:00:00 GMT+0000 (Hora padrão de GMT)
result: 2
result UTC: 2
In the first example, getMonth returns 7 and getUTCMonth returns 8. In the second example, both returns the same value 2.
Does anyone already experiences this situation? I am from Portugal and i think that it has something to be with my GMT but i don't understand why this is happening, because the examples are running in same circumstances.
Thanks in advances

You will see that, depending on YOUR TIMEZONE, the console logs may be different. I chose the first of the month '01' because it will be given a midnight default time '00:00:00', which will result in some timezones yielding February instead of March (you can get the full scoop here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) :
let date1 = '2019-03-01'; // defaults to UTC
let date2 = '2019-03-01T14:48:00'; // LOCAL date/time
let dt1 = new Date(date1);
let dt2 = new Date(date2)
let month1 = dt1.getMonth();
let month2 = dt2.getMonth();
console.log("mon1: " + month1);
console.log("mon2: " + month2);

You will find that it is caused by DST difference.

Universal Time Zone date methods are used for working with UTC dates
Date returns month between 0 to 11
new Date(1976, 01 , 18) -
Wed Feb 18 1976 00:00:00 GMT+0530 (India Standard Time)
*getUTCDate return same as getDate() but returns Date based on World Time Zone, same with month and year
new Date(1976, 01 , 18).getUTCDate() -
17
new Date(1976, 01 , 18).getDate() -
18
new Date(1976, 02 , 18).getUTCMonth() -
2
new Date(1976, 01 , 18).getMonth() -
1
new Date(1976, 01 , 18).getYear() -
76
new Date(1976, 01 , 18).getUTCFullYear() -
1976
new Date(1976, 01 , 18).getFullYear() -
1976

A Date in js is just a timestamp, meaning there is no timezone information in any Date instance. A date is an absolute timed event (in opposition to a wall clock time which is relative to your timezone).
So… when you print the date to the console, because there is no timezone information in the date object, it will use your browser's timezone to format the date.
This is embarrassing because if you provide the same date to 2 clients, one in US and the other one in EU and ask them the date's month, because both are using their own timezone, you might end up with different answers.
To prevent this, getUTCMonth(); will use a default timezone of UTC (+0) instead of the client's browser so that the answer will be consistent whatever the client's timezone.

Related

How to handle date and time during conversion?

I'm trying to convert the time from AEST to IST. Not sure whether this approach is correct. My question with the below code is how can I deduct the date by 1 if the time shifts to the previous day?
The output should result : Thu Aug 24 2022 07:45:00
const date = 'August 25, 2022 12:15:00' // GMT+1000 (Australian Eastern Standard Time)" in 24 hours format
var IST = new Date(date);
IST.setHours(IST.getHours() - 5);
IST.setMinutes(IST.getMinutes() + 30);
console.log(IST.toString())

How to set date always to eastern time regardless of user's time zone

I have a date given to me by a server in unix time: 1458619200000
NOTE: the other questions you have marked as "duplicate" don't show how to get there from UNIX TIME. I am looking for a specific example in javascript.
However, I find that depending on my timezone I'll have two different results:
d = new Date(1458619200000)
Mon Mar 21 2016 21:00:00 GMT-0700 (Pacific Daylight Time)
// Now I set my computer to Eastern Time and I get a different result.
d = new Date(1458619200000)
Tue Mar 22 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
So how can I show the date: 1458619200000 ... to always be in eastern time (Mar 22) regardless of my computer's time zone?
You can easily take care of the timezone offset by using the getTimezoneOffset() function in Javascript. For example,
var dt = new Date(1458619200000);
console.log(dt); // Gives Tue Mar 22 2016 09:30:00 GMT+0530 (IST)
dt.setTime(dt.getTime()+dt.getTimezoneOffset()*60*1000);
console.log(dt); // Gives Tue Mar 22 2016 04:00:00 GMT+0530 (IST)
var offset = -300; //Timezone offset for EST in minutes.
var estDate = new Date(dt.getTime() + offset*60*1000);
console.log(estDate); //Gives Mon Mar 21 2016 23:00:00 GMT+0530 (IST)
Though, the locale string represented at the back will not change. The source of this answer is in this post. Hope this helps!
Moment.js (http://momentjs.com/timezone) is your friend.
You want to do something like this:
var d = new Date(1458619200000);
var myTimezone = "America/Toronto";
var myDatetimeFormat= "YYYY-MM-DD hh:mm:ss a z";
var myDatetimeString = moment(d).tz(myTimezone).format(myDatetimeFormat);
console.log(myDatetimeString); // gives me "2016-03-22 12:00:00 am EDT"
For daylight saving, Eastern time become 4 hours behind UTC. That's why its offset is -4x60 = -240 minutes. So when daylight is not active the offset will be -300. The offset variable's value is the key point to be noted here. Kindly see this code in action in attached image.
var offset = new Date().getTimezoneOffset();// getting offset to make time in gmt+0 zone (UTC) (for gmt+5 offset comes as -300 minutes)
var date = new Date();
date.setMinutes ( date.getMinutes() + offset);// date now in UTC time
var easternTimeOffset = -240; //for dayLight saving, Eastern time become 4 hours behind UTC thats why its offset is -4x60 = -240 minutes. So when Day light is not active the offset will be -300
date.setMinutes ( date.getMinutes() + easternTimeOffset);

SQL statement querying result which is within a time range

I want to do a sql statement which queries by timestamp using javascript.
Here is how i set my timestamp:
var startTime = new Date(year, month, day, 0, 0);
var endTime = new Date(year, month, day, 23, 59);
My sql statement is:
'SELECT * FROM proximate.user WHERE join_timestamp >= $1 ' +
'AND join_timestamp<=$2 ORDER BY user_id ASC';
$1 is startTime and $2 is endTime. Given if the startTime is Sat Dec 01 2012 00:00:00 GMT+0800 (SGT) and endTime is Sat Dec 01 2012 23:59:00 GMT+0800 (SGT), the executed statement returns results which include timestamp that is a day before the startTime.
Anyone has any idea why?
Thanks in advance.
My guess is that you receive proper results but forget to convert timestamp column of returned resultset to GMT+8 : "Sat Dec 01 2012 00:00:00 GMT+0800" = Fri Nov 30 2012 16:00:00 UTC". Another option - pass dates in UTC. Actually that depends on what you want to get: if you need all users who joined on December 1st GMT+8 you need to convert result set, if you need users who joined on December 1st UTC, pass UTC dates :"Sat Dec 01 2012 00:00:00 UTC"

Problem in adding days / month / year to a given date using javascript?

I trying to add days / months / year to a given date and map it to an input field
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setYear(2011);
document.getElementById("test").innerHTML=d;
d.setDate(d.getDate()+20);
document.getElementById("test").innerHTML+=""+d.getDate()+"/"+d.getMonth()+"/"+d.getYear("YY");
this actually prints out
Fri Jul 15 2011 12:45:48 GMT+0530 (India Standard Time)
4/7/111
actually this is wrong.. it should print out 5/7/2011.. i think by default the system takes as "30" days for a month and adds the +20 days.. but actually Jun has 30 days so that result should be 5/7/2011..
any suggestion about what goes wrong in here.. any alternative for this?
At the first, you have better to use getFullYear to get year as 2011. You did get number from getDate() and add 20. This break Date. You should get long value from getTime(), and add milli-seconds.
<div id="test"></div>
<script>
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setFullYear(2011);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
d.setTime(d.getTime()+1000*60*60*24*20);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
</script>
> var d = new Date();
> d.setDate(15);
> d.setMonth(06);
> d.setYear(2011);
is equivalent to:
var d = new Date(2011,6,15); // 15 Jul 2011
Months are zero based (January = 0, December = 11).
Date.prototype.getYear is specified in ECMA-262 ed5 as Return YearFromTime(LocalTime(t)) − 1900. so:
alert(d.getYear()); // 111
whereas:
alert(d.getFullYear()); // 2011
i think by default the system takes as "30" days for a month and adds the +20 days.. but actually May has 31 days so that result should be 5/7/2011.
You are interpreting it a wrong way, Month in a date starts with 0 - Jan..
So as per the date entered by you it comes Jul 15 2011 on the month number 6.
When you add 20 to date it will be Aug 04 2011 and you are directly getting month number which is 7 - i.e. Aug which misleads your calculation. And for the year, yes it is you should getFullYear
Read this to get your basics correct..

Adding a week to Date in JavaScript: rounding error or daylight savings?

I am trying to add seven days to a Data object, however at some stage I start getting strange results.
var currDate = new Date(2011, 2, 28)
, oldTicks = currDate.getTime()
, newTicks = oldTicks + (86400000 * 7)
, nextWeek = new Date(newTicks)
console.log('Old ticks: ' + oldTicks)
console.log('New ticks: ' + newTicks)
console.log('New date : ' + nextWeek)
The output I get, both Chrome/FF is:
Old ticks: 1301230800000
New ticks: 1301835600000
log: New date : Sun Apr 03 2011 23:00:00 GMT+1000 (EST)
Expected to get:
log: New date : Mon Apr 04 2011 23:00:00 GMT+1000 (EST)
As you can see, instead of adding 7 days, just 6 were added. The code above, however, works fine with other dates, say 2011 Apr 28 or 2011 May 28.
Crescent Fresh is correct form what I can deduce.
Looking up timezones GMT+1000 (EST) looks like Australia Eastern Standard Time - from wikipedia - list of timezones by UTC offset
And from wikipedia - daylist savings time around the world, shows that Australia switches from standard to daylight savings time in between the date ranges specified by the OP.
If it were me I'd do:
var curDate = new Date(),
var aWeekLater = new Date(curDate.getFullYear(), curDate.getMonth(), curDate.getDate() + 7);
with some possible adjustments for time of day.
That said, when I try your code in my Chrome developer console, I get 04 Apr as the answer.

Categories

Resources