JavaScript Date.toJSON() produces a date which has wrong hours and minutes - javascript

I want to print a Date to ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ so I used the following lines of code, but I am getting unexpected output
var date = new Date(2012, 10, 30, 6, 51);
print('UTC Format: '+date.toGMTString());
print('toString() method: '+date.toString());
print('toJSON() method: '+date.toJSON());//print hours and minutes incorrectly
print('to UTCString() method: ' + date.toUTCString());
The corresponding output is
UTC Format: Fri, 30 Nov 2012 01:21:00 GMT
toString() method: Fri Nov 30 2012 06:51:00 GMT+0530 (India Standard Time)
toJSON() method: 2012-11-30T01:21:00.000Z
to UTCString() method: Fri, 30 Nov 2012 01:21:00 GMT
The toJSON() method prints hours and minutes incorrectly but toString() prints it correctly, I wanted to know what is the reason for that.
Do I have to add time offset to the Date object, if yes then how?

var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());

date.toJSON() prints the UTC-Date into a string formatted as json-date.
If you want your local-time to be printed, you have to use getTimezoneOffset(), which returns the offset in minutes. You have to convert this value into seconds and add this to the timestamp of your date:
var date = new Date(2012, 10, 30, 6, 51);
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON()
In a previous version of this answer, the offset was erroneously added instead of subtracted.

Related

JS setHours on date is not working correctly

I have the following code to increment the hours in a date:
let timerExpireDate = new Date(countdownStartDate);
console.log(`original date is ${timerExpireDate}`);
console.log(`add on ${countdownHours} hours`);
timerExpireDate.setHours(timerExpireDate.getHours() + countdownHours);
console.log(`New date is ${timerExpireDate}`);
However it also seems to be incrementing the days by 6, here is the console log:
original date is Sun Jul 19 2020 16:36:39 GMT+0800 (Taipei Standard Time)
add on 2 hours
New date is Sat Jul 25 2020 18:36:39 GMT+0800 (Taipei Standard Time)
What am I doing wrong here?
It is likely that countdownHours is of type string instead of number, so timerExpireDate.getHours() + countdownHours is '162' (6 days later) instead of 18.
The fix is to cast countdownHours to number first, like countdownHours = +countdownHours.

get the current date from GMT

I want to get the date from the GMT time but it returns the date which is one day ahead. How can I get the date mentioned in the GMT string always?
new Date("Mon, 27 Aug 2018 22:00:00 GMT").getDate()
This command returns 28 as the output, but I want 27.
Is there anything I need to add?
Thanks in advance.
Try this One.I think your problem will be solved.
<script>
function myFunction() {
var d = new Date();
var n = d.getUTCDate();
document.getElementById("demo").innerHTML = n;
}
</script>
When you create a new Date() the browser returns date based on your device timezone. You can use Date.getTimezoneOffset() to get GMT offset time difference and then adjust the time by multiplying the value.
// Your date
var myDate = new Date("Mon, 27 Aug 2018 22:00:00 GMT")
// Convert your date to local using getTimezoneOffset() and multiply with 60000 to get time adjusted GMT 0
var myDateLocal =new Date( myDate.valueOf() + myDate.getTimezoneOffset() * 60000 ).getDate();
document.getElementById("myDate").innerHTML=myDateLocal;
<h1 id="myDate" ></h1>

Compare Date 1 and Date 2 with 10 minutes

This is how I calculate the duration:
var duration = new Date().getTime() - customerForgotPassword[0].createdTime.getTime();
This is how I compare:
var TEN_MINUTES = 10*60*1000;
if(duration > TEN_MINUTES){
//do smtg
}
new Date().getTime() returns 1528291351108 which is Wed Jun 06 2018 13:22:31 in UTC
customerForgotPassword[0].createdTime returns Wed Jun 06 2018 13:20:04 GMT+0800 (Malay Peninsula Standard Time) in my code.
customerForgotPassword[0].createdTime.getTime() returns 1528262404000 which is Wed Jun 06 2018 05:20:04 in UTC
In database, customerForgotPassword[0].createdTime is in UTC format but when I retrieve it, it shows the local timezone. How can I set this to UTC format too when I retrieve it in node.js using Sequelize ?
I had to add 8 hours to get time in UTC
var timeInUTC = customerForgotPassword[0].createdTime.getTime() - (customerForgotPassword[0].createdTime.getTimezoneOffset() * 60 * 1000)

How to Convert Hard Coded date into standard GMT format

I need to convert a hard coded date into a standard GMT format.How can I do this?
The date I have is in the following format:
var myDate = 'dd|mm|yyyy';
There is no time or day description in the date.Just the 'dd|mm|yyyy' string.
Is there a way I can convert it into GMT?
Thanks in advance.
a = '22/02/2014'.split('/')
d = new Date(a[2],parseInt(a[1], 10) - 1,a[0])
//Sat Feb 22 2014 00:00:00 GMT+0530 (India Standard Time)
Now you have a javascript date object in d
utc = d.getUTCDate() + "/" + (d.getUTCMonth() + 1 ) + "/" + d.getUTCFullYear();
//"21/2/2014" for an accurate conversion to UTC time of day is a must.
If you are in say India, the Javascript Date object will have timeZoneOffset 330. So its not possible to keep a javascript Date object with timezone GMT unless your system time is GMT.
So if you want a Date object for calculation, you can create one with localTimezone and simply suppose it is GMT
pseudoGMT = new Date( Date.parse(d) + d.getTimezoneOffset() * 60 * 1000);
//Fri Feb 21 2014 18:30:00 GMT+0530 (India Standard Time)
If you can explain your high level requirement we might be able to help with some alternate solutions.
Use regex matching to extract the data you need:
var myDate = "21|01|2014";
var data = myDate.match(/(\d{2})\|(\d{2})\|(\d{4})/);
var date = new Date(data[3], data[2] - 1, data[1]);
Note that the month is 0-indexed, so january = 0
More on regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories