简体   繁体   中英

Convert date from UTC to EST (Javascript, HTML)

I am using Vue to render some data, the problem is the date stored in the field created_at is in UTC (I need it to be in EST).

    <div class="row">
        <div class="col-md-3" v-for="result in results">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <p>createdAt:{{ result._source.created_at }}
                </div>
                <div class="panel-body">
                    <p>text:{{ result._source.text }}</p>
                </div>
            </div>
        </div>
    </div>

I tried using this javascript variable to convert it but I'm not sure how to implement it.

<script>
   var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
   console.log('USA time: '+ (new Date(usaTime)).toISOString())
</script>

Do I need to pass the value of created_at into a javascript function that will convert the date? Or could I just subtract eight hours from the date and then return it?

If you have a Date object which is in UTC, you can use your code to display it in a locale and timezone much as you did in your code.

Live demo:

 var utcTime = new Date("2020-10-16T18:00:00Z"); console.log('UTC Time: ' + utcTime.toISOString()); var usaTime = utcTime.toLocaleString("en-US", {timeZone: "America/New_York"}); console.log('USA time: '+ usaTime)

So

Do I need to pass the value of created_at into a javascript function that will convert the date?

Yes, assuming your result._source.created_at value is formatted as a UTC date, you would pass it in and call toLocaleString to display it appropriately.

Perhaps something like:

<div class="panel-heading">
      <p>createdAt:{{ new Date(result._source.created_at).toLocateString("en-US", {timeZone: "America/New_York") }}</p>
 </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM