Reputation: 269
i am trying to convert a string into date type.i am giving the string value to new date(). but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
Upvotes: 1
Views: 402
Reputation: 41
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W
Upvotes: 0
Reputation: 8082
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that, This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
Upvotes: 1
Reputation: 16777
JavaScript Date
objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format
function to turn it into MM/DD/YYYY
format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString
before mine.)
Upvotes: 0
Reputation: 43557
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530
. Your original date has .000Z
that is time zone of GMT +0
.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
Upvotes: 0
Reputation: 26
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
Upvotes: 0