48

Okay, say JSON parse string UTC date as below:

2012-11-29 17:00:34 UTC

Now if I want to convert this UTC date to my local time, how can I do this?

How do I format it to something else like yyyy-MM-dd HH:mm:ss z?

This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out :/

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
lannyboy
  • 843
  • 1
  • 12
  • 22
  • 3
    `new Date("2012-11-29 17:00:34 UTC")` will be in the local time of the client who is using the page – Esailija Nov 29 '12 at 09:05
  • You could split it into array using spaces or the symbols. Suppose you do .split(" ") and array with with date and time and "utc" will be formed. then split it again like this .split("-") and split the time like this .split(":") and so on. – yashas123 Dec 20 '17 at 16:19
  • Just for anyone googling here. It's worth remembering that in MYSQL it's incredibly easy to absolutely perfectly convert to any time zone (and that includes perfectly caring for daylight savings times). Since almost all data comes from mysql on the server, it's worth bearing this in mind. – Fattie Oct 21 '20 at 14:18

10 Answers10

56

Try:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
  • 13
    well, I tried out IE and Firefox, they are all NAN! Invalid Date? – lannyboy Nov 29 '12 at 14:46
  • using the date.js library [this works](http://jsfiddle.net/brmr3623/7/) for the date format yyyy-MM-dd HH:mm:ss – Pradyut Bhattacharya Aug 25 '14 at 12:05
  • 2012/11/29 <--try this – aztack Jan 10 '17 at 05:58
  • This is then relative to the time zone of the client right? How would you go about this if you have many dates in UTC stored, but on a site you would need it to be in a specific local time for ALL clients? – ffritz May 31 '17 at 17:45
  • 4
    This will only work with chrome browser, this will not work in mozilla firefox and IE11. do you have any solution for all other browsers? – Hardik Jul 27 '17 at 07:08
  • 3
    seems silly that there isnt a method on the `Date` prototype to return a date object in the local time instead of GMT/UTC – oldboy Feb 11 '20 at 00:33
42
var offset = new Date().getTimezoneOffset();

offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.

utc_date.setMinutes(utc_date.getMinutes() - offset);
Guy Passy
  • 694
  • 1
  • 9
  • 32
Surabhi
  • 3,508
  • 2
  • 17
  • 12
  • 5
    I think that's supposed to be subtract the offset, not add the offset. – OnResolve Apr 23 '13 at 15:26
  • 1
    + is appropriate because if the time zone is behind 1 hour, the value returned will be -60. – Kelso Sharp Sep 05 '14 at 13:43
  • 4
    @OnResolve Surabhi is correct with using `+`. When using `date.getTimezoneOffset`, _"a negative return value from getTimezoneOffset() indicates that the current location is ahead of UTC, while a positive value indicates that the location is behind UTC."_ ([**Tech Republic**](http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/)). – WebWanderer Apr 03 '15 at 16:21
  • 2
    At least in chrome this is false. Even negative time zones return as a positive number. – KingOfHypocrites Jun 05 '15 at 20:43
  • 2
    @Surabhi @WebWanderer that explanation shows why using `+` here is incorrect. The value returned from `getTimezoneOffset()` is the value you need to **add to a local time to get to UTC**. So if you have want to go from UTC to local time, the action needs to be `-`. Basically, this answer does the opposite of the request, converting from local time to utc. – Guy Passy Apr 17 '16 at 14:37
  • Ah, yes @GuyPassy , you're correct, how embarrassing. Timestamp conversion can get very confusing. Thank you for clarifying. `- offset` is the correct way. – WebWanderer Apr 18 '16 at 14:24
  • This is the easiest solution that works on both chrome and safari (ios/android mobile) for me. – Trevor Panhorst Jan 12 '17 at 21:29
  • 1
    if you already have a date, make sure to use THAT date to get the offset from, or else you may end up with the wrong offset. date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); – Don Rolling Jan 31 '17 at 16:21
4

Here is another option that outputs mm/dd/yy using toLocaleString():

const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • This one is my favorite. To expand on it a bit, `toLocaleString` will use the local timezone, but you can also feed it options to get different timezones or display formats. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString for details. – Mat Schaffer Jun 29 '22 at 07:13
2

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

Praveen
  • 55,303
  • 33
  • 133
  • 164
1

The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format

Khaled Al-Ansari
  • 3,910
  • 2
  • 24
  • 27
1

You could take a look at date-and-time api for easily date manipulation.

let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
0

This should work

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
Murali N
  • 3,451
  • 4
  • 27
  • 38
0

This works for both Chrome and Firefox.
Not tested on other browsers.

const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
  if (dateTime !== null && dateTime !== undefined) {
    if (notStanderdFormat) {
      // works for 2021-02-21 04:01:19
      // convert to 2021-02-21T04:01:19.000000Z format before convert to local time
      const splited = dateTime.split(" ");
      let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
      const date = new Date(convertedDateTime);
      return date.toString();
    } else {
      // works for 2021-02-20T17:52:45.000000Z or  1613639329186
      const date = new Date(dateTime);
      return date.toString();
    }
  } else {
    return "Unknown";
  }
};

// TEST

console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
w0lf
  • 353
  • 3
  • 10
0
// d = "2021-09-23T15:51:48.31"

console.log(new Date(d + "z").toLocaleDateString());  // gives 9/23/2021

console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
-8
/*
 * convert server time to local time
 *  simbu
*/
function convertTime(serverdate) {
    var date = new Date(serverdate);
    // convert to utc time
    var toutc = date.toUTCString();
    //convert to local time
    var locdat = new Date(toutc + " UTC");
    return locdat;
}