admin管理员组

文章数量:1401772

I am using laravel 5.7 for api and vue for front end. In api response I am getting a user's last seen timestamp as last_seen: "2019-04-17 05:20:37" which is by default in UTC format.

Laravel API code:

$user_details = array(
            'user_id' => $userId,
            'name' => $userDetails->name,
            'email' => $userDetails->email,
            'phone' => $userDetails->contact,
            'account_creation_date' => $userDetails->created_at->toDateTimeString(),
            'last_seen' => $lastSeen != null ? $lastSeen->toDateTimeString() : $userDetails->last_login->toDateTimeString(),
            'language' => 'English',
            'country' => $country->name
        );

$user_profile['user_details'] = $user_details;
return response()->api(true, 'Success', $user_profile);

This the api response I am getting:

On the front end i.e in vue I am using Dayjs Package to show user's last seen as [Day|Hours|Minutes] ago but the problem is intended user has logged in just now but I am getting it is showing 6 Hours ago

Since I am in Asia/Kolkata timezone the code is taking 5.5/6 hours also in consideration.

Also I tried with moment.js but I get undefined function moment.tz.guess() error

This is what I have tried so far:

I am passing the datetime string to my vuejs function:

import dayjs from "dayjs";

convertFromNow(date) {
 return dayjs(date).fromNow();
},

and then call this method to print as 1 minute ago.

<div class="side-box mt-4">
                  <h2 class="side-head">
                    <i class="fa fa-clock-o" />
                    {{ convertFromNow(userInfo.user_details.last_seen) }}
                    <h6 class="text-gray">
                      Last seen
                    </h6>
                  </h2>
                </div>

Expected results I need is I should get user's last seen as per my timezone no matter what is UTC time.

I am using laravel 5.7 for api and vue for front end. In api response I am getting a user's last seen timestamp as last_seen: "2019-04-17 05:20:37" which is by default in UTC format.

Laravel API code:

$user_details = array(
            'user_id' => $userId,
            'name' => $userDetails->name,
            'email' => $userDetails->email,
            'phone' => $userDetails->contact,
            'account_creation_date' => $userDetails->created_at->toDateTimeString(),
            'last_seen' => $lastSeen != null ? $lastSeen->toDateTimeString() : $userDetails->last_login->toDateTimeString(),
            'language' => 'English',
            'country' => $country->name
        );

$user_profile['user_details'] = $user_details;
return response()->api(true, 'Success', $user_profile);

This the api response I am getting:

On the front end i.e in vue I am using Dayjs Package to show user's last seen as [Day|Hours|Minutes] ago but the problem is intended user has logged in just now but I am getting it is showing 6 Hours ago

Since I am in Asia/Kolkata timezone the code is taking 5.5/6 hours also in consideration.

Also I tried with moment.js but I get undefined function moment.tz.guess() error

This is what I have tried so far:

I am passing the datetime string to my vuejs function:

import dayjs from "dayjs";

convertFromNow(date) {
 return dayjs(date).fromNow();
},

and then call this method to print as 1 minute ago.

<div class="side-box mt-4">
                  <h2 class="side-head">
                    <i class="fa fa-clock-o" />
                    {{ convertFromNow(userInfo.user_details.last_seen) }}
                    <h6 class="text-gray">
                      Last seen
                    </h6>
                  </h2>
                </div>

Expected results I need is I should get user's last seen as per my timezone no matter what is UTC time.

Share Improve this question edited Apr 17, 2019 at 6:27 Dinesh Suthar asked Apr 17, 2019 at 5:36 Dinesh SutharDinesh Suthar 8801 gold badge17 silver badges47 bronze badges 10
  • 1 What is the problem in using moment.js? It is a great library. – iwaduarte Commented Apr 17, 2019 at 5:37
  • @iwaduarte there is no problem in using moment.js but I am getting error in guessing user's timezone. – Dinesh Suthar Commented Apr 17, 2019 at 5:39
  • Also refer to this link to understand what is happening with your code. github./moment/moment-timezone/issues/523 . Could you please also edit your question to include the code you are using with moment.js ? – iwaduarte Commented Apr 17, 2019 at 5:40
  • 1 Why is your API returning date/time strings without timezone information? IMHO, the best transport format for dates is ISO 8601, ie 2019-04-17T05:20:37Z. This makes it unambiguous and JS can parse it correctly. In my browser, parsing your "2019-04-17 05:20:37" string treats it as local time (which seems to be your problem) – Phil Commented Apr 17, 2019 at 5:43
  • You can get user's current time using toLocaleString() – Akshay Commented Apr 17, 2019 at 5:45
 |  Show 5 more ments

4 Answers 4

Reset to default 2

Here is my solution in Vanilla JavaScript (without depending on external libraries such as moment.js or days.js).

The trick is to append 'UTC' to your date string, before converting it to a JavaScript Date object.

const dateString = '2019-04-17 05:20:37';
const localDate = new Date(`${dateString} UTC`);
console.log(localDate)

If you run the above code on your local browser (Chrome) console, it should print the time based on your (or your users') local timezone.

You also try to use moment.js, you need to tell moment time is in UTC

console.log(moment.utc("2019-04-17 05:20:37").fromNow())
<script src="https://momentjs./downloads/moment.js"></script>

My understanding of your question is that you need to get the user's timezone (through their browser). I will demonstrate this using moment's cdn.

You need to have both moment.js and moment-timezone-with-data.js:

<script type="text/javascript" src="https://cdn.jsdelivr/momentjs/latest/moment.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare./ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.js"></script>

Then using this function: moment.tz.guess(); in your code should give you the user's timezone.

After this, you can pass the timezone you get to your API to retrieve the correct time for this timezone.

As a plus, if you're using Carbon you (might) need to use setTimezone():

Carbon::parse($time)->setTimezone($tz);

Others see: https://momentjs./timezone/docs/#/using-timezones/guessing-user-timezone/

Your date/time string "2019-04-17 05:20:37" may represent a UTC time but JavaScript will parse it as a local time, meaning the times will always be wrong.

The very simple answer is to use an unambiguous format like ISO 8601 / Atom, eg

"2019-04-17T05:20:37+00:00"

Carbon provides an easy method that you can drop-in as a replacement for toDateTimeString()

$user_details = [
    // snip
    'account_creation_date' => $userDetails->created_at->toAtomString(),
    'last_seen' => $lastSeen != null ? $lastSeen->toAtomString() : $userDetails->last_login->toAtomString(),
    // snip
];

See https://carbon.nesbot./docs/#api-monformats

本文标签: javascriptHow to convert a UTC datetime string into users39 current timezoneStack Overflow