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?

1
  • 1
    Hi what have you tried so far? Commented Apr 29, 2019 at 7:24

4 Answers 4

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() );

Sign up to request clarification or add additional context in comments.

3 Comments

@SyedMehtabHassan There is no need to call Date.parse since Date will parse the argument since it is a string.
sorry i just want to edit my answer and edit yours by mistake
@SyedMehtabHassan Ok :) Happy editing!
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>

8 Comments

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 ?
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.
@user3348410 what output you expect ?
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
|
-1

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

2 Comments

It's give me "2019-04-29T18:40:24+03:00" something like this. i didn't understand what is this mean
what date time object you passed to moment?
-2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.