0

My database value is this

2020-03-08 20:44:00

But in javascript. It display

Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)

Want i want to display on UI

2020-03-08 20:44:00

or

2020-03-08

Is there a way to remove the timezone and get only the actual value from the database.

Paul White
  • 97
  • 2
  • 10

6 Answers6

2

toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.

var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;

console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);
jaydeep
  • 96
  • 4
0

You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.

If date is the variable that you get from your database, then you can format it like you want it like this:

let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')

This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.

Samyok Nepal
  • 535
  • 3
  • 15
0

Try this.

 let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
0

You can take each part of the date and construct your own format example:

let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()

in this example: my_date hold the date you want to display.

U.P
  • 7,357
  • 7
  • 39
  • 61
0

If you're able to use a library, use moment.js

https://momentjs.com/docs/#/displaying/

moment("2020-03-08 20:44:00").format("YYYY-MM-DD");

or

moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");

It can even change the time to utc

https://momentjs.com/guides/#/parsing/local-utc-zone/

moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");

hope this helps :)

Don F.
  • 123
  • 8
-2

Subtract your timezone offset milliseconds.

var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);
StackSlave
  • 10,613
  • 2
  • 18
  • 35