-2

My current time zone is getting added when converting date using "new Date()".

var date = "2019-06-03T23:32:59.2354387Z";
var date1 = new Date(date);
console.log(date1);

Expected result: 03-Jun-19 23:32:00

Actual result: 04-Jun-19 02:32:00

please find the fiddle here

https://jsfiddle.net/as6htw9p/

biju m
  • 79
  • 1
  • 12
  • 3
    Why May is expected? – Banzay Jun 03 '19 at 13:49
  • How are you getting your _actual_ result? Depending on how it's output, it will output in _local time_ unless you explicitly specify output in UTC time. – Martin Jun 03 '19 at 13:52
  • 1
    This has nothing to do with jQuery. –  Jun 03 '19 at 13:54
  • 3
    Possible duplicate of [Is the Javascript date object always one day off?](https://stackoverflow.com/questions/7556591/is-the-javascript-date-object-always-one-day-off) – Heretic Monkey Jun 03 '19 at 13:56

2 Answers2

0

Date output in JavaScript is by default in local time. You should use UTC get/set if you need GMT format.

Try this:

utc_date = date1.toUTCString();
console.log(utc_date);
  • Ultimately I need to display the date time in "dd/MMM HH:mm" format. Hence I may need to again convert this utc string to date and format it. – biju m Jun 03 '19 at 16:18
  • You can get separately day, month, year, hour, etc in UTC from date1 and construct the output string as you desire. Ex: date1.getUTCDate() will give the day, date1.getUTCMonth() + 1 will give you the month, and so on. – Marius Danciu Jun 03 '19 at 20:51
0

More specific to your scenario with keeping the format, this should work. It's just a shame that the integers provided are formatted like '1' instead of '01' so I have had to add a ‘0’ to the start of the variables.

This should output the exact result you want.

var date = new Date();
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']

var day = '0' + (date.getDay() + 2); // 003
day = day.slice(-2) + '-'; // 03-

var month = date.getMonth(); // 5
month = monthNames[month]; // Jun
month = month + '-'; // Jun-

var year = date.getFullYear() + ''; // 2019
year = year.slice(-2) + ' '; // 19

var hour = '0' + date.getHours(); // 018
hour = hour.slice(-2) + ':'; // 18:

var minutes = '0' + date.getMinutes(); // 025
minutes = minutes.slice(-2) + ':'; // 25:

var seconds = '0' + date.getSeconds(); // 06
seconds = seconds.slice(-2); // 06

var now = day + month + year + hour + minutes + seconds;
Indecisive
  • 66
  • 3