0

I try to build jquery countdown timer, but the end date is in mysql database with timestamp custom format

here is my saved date in database.

2019-01-09 12:48:29

That date is GMT+0000 which is UTC. But when I try to show it in javascript like below

var countdown = new Date("<?php echo $getDate['date_end'];?>");
console.log(countdown);

It will show output

Wed Jan 09 2019 12:48:29 GMT+0700 (GMT+07:00)

That's is wrong, because when I save the $getDate['date_end'] to my database is in UTC format (+0000) why it becomes GMT +0700 in javascript?

I try to convert it to UTC with this code

var countdown = new Date("<?php echo $getRound['date_end'];?>");
var a = countdown.toUTCString();
console.log(a);

but the output will give different hours

Wed, 09 Jan 2019 05:48:29 GMT
  • 1
    Probably because the JS date method is returning your local date/time and the server is in another location, or vice-versa. – Funk Forty Niner Jan 08 '19 at 16:09
  • 1
    `If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings for timezone offset.` [src](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#JavaScript_Date_instances) You'll need to specify the timezone when you create the date in javascript – aynber Jan 08 '19 at 16:10
  • so I need to get the timezone offset then add to the time? – Investor Support Jan 08 '19 at 16:14
  • Use this: `countdown = new Date(countdown.getTime() - countdown.getTimezoneOffset() * 60000);` –  Jan 08 '19 at 16:16

1 Answers1

0

If all of the datetime values in your database are stored in UTC, then you can create the js date object in UTC using new Date(Date.UTC(...)) after parsing the datetime string from your database. It is not recommended to parse datetime strings with new Date() due to inconsistent browser implementations, so the example below includes some manual parsing and adjustment of the month value to the month indexes used in js.

const s = '2019-01-09 12:48:29';
const [y, m, d, hh, mm, ss] = s.match(/\d+/g);
const utc = new Date(Date.UTC(y, m - 1, d, hh, mm, ss));
console.log('OUTPUT may vary:', utc);
console.log('UTC datestring:', utc.toUTCString());
console.log('Local datestring:', utc.toLocaleString());
benvc
  • 14,448
  • 4
  • 33
  • 54