0

if i have some time with UTC now. which coming from backend in json format like:

cache_time: "2019-04-29 06:12:06"

and eg. some user will open page in some another country or city. How i can convert it to this user time with javascript?

user3348410
  • 2,733
  • 10
  • 51
  • 85

4 Answers4

0

Use the Moment.js libary:

date = new Date("2019-04-29 06:12:06Z");

var withoutUTC = moment(date).toString();
var withUTC = moment.utc(date).toString();
console.log(withoutUTC)
console.log(withUTC)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
Malekai
  • 4,765
  • 5
  • 25
  • 60
Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
  • It's mean this date 2019-04-29 06:12:06 so when time was 06:12:06 on my computer my time was a 03:12:06 right ? – user3348410 Apr 29 '19 at 07:33
  • No, this gives a date and time in the users time-zone. Add a 'Z' to the end of the timestamp, and Date will understand that it is UTC and will display it in the users timezone. – some Apr 29 '19 at 07:33
  • [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Apr 29 '19 at 12:42
  • @user3348410 what output you expect ? – Syed Mehtab Hassan Apr 29 '19 at 13:00
  • I understand that: it's give me difference with utc time and my local time. so +03.00 hours. Everything well. But how i can show it like 2019-04-29 ' here sum of this difference time' eg: if utc is 12:00 and difference 3 hour i would show it like: 2019-04-29 15:00 – user3348410 Apr 29 '19 at 13:02
  • @user3348410 you want to show the date part only? – Syed Mehtab Hassan Apr 29 '19 at 13:05
  • No i want to show updated date and time with difference. So more readable 2019-04-29 06:12:06 like this. just calculated version with difference – user3348410 Apr 29 '19 at 13:06
  • @user3348410 check – Syed Mehtab Hassan Apr 29 '19 at 13:24
0

A string with "2019-04-29 06:12:06" does not indicate the time zone. If you add a 'Z' at the end, the built in Date function understands that the time is in UTC.

const cache_time = "2019-04-29 06:12:06";

const date = new Date ( cache_time + "Z" );
console.log("UTC TIME", date.toISOString())
console.log("LOCAL TIME", date.toLocaleString() );
some
  • 48,070
  • 14
  • 77
  • 93
-1

Use moment.js to convert utc to local time.In your case: moment().utc("2019-04-29 06:12:06").local().format()

-2

Or you can use spacetime.js, which is based on moment.js and takes into consideration also timezones. const localTimeDate = spacetime().now().format();

Martin Spd
  • 53
  • 1
  • 4