最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert UTC time ONLY to local time ONLY (without date) using javascript or momentjs - Stack Overflow

programmeradmin1浏览0评论

I am fetching a string from database which is in a 24hr format and is stored in UTC time. For example "18:00:00". I would want this time to be converted into local time only (no date is required), wherever the time zone may be and display it in 12hr format. For example, if the timezone is Australian Eastern Standard Time, I have to find out the time difference which is 11 hrs ahead of UTC time and display it as "05:00 AM" and also do the vice versa of local time only into UTC time only (no date is required) so that I can save it back to database. I have searched a lot for it but everyone mentions about converting date object from UTC to local or vice versa but not for time only. Please help me out with this.

I am fetching a string from database which is in a 24hr format and is stored in UTC time. For example "18:00:00". I would want this time to be converted into local time only (no date is required), wherever the time zone may be and display it in 12hr format. For example, if the timezone is Australian Eastern Standard Time, I have to find out the time difference which is 11 hrs ahead of UTC time and display it as "05:00 AM" and also do the vice versa of local time only into UTC time only (no date is required) so that I can save it back to database. I have searched a lot for it but everyone mentions about converting date object from UTC to local or vice versa but not for time only. Please help me out with this.

Share Improve this question asked Nov 21, 2017 at 6:27 suvenksuvenk 5171 gold badge11 silver badges27 bronze badges 2
  • What is you input? How you are getting date value from db? – Durga Commented Nov 21, 2017 at 6:29
  • In db the Data Type is "time(0)". So when I fetch it from db, it is a string in the UI. I am using SQL Server db and .NET in the backend and Angular in the frontend – suvenk Commented Nov 21, 2017 at 6:33
Add a ment  | 

1 Answer 1

Reset to default 13

let utcTime = "18:00:00";
let utcText = moment(utcTime,'HH:mm').format("HH:mm");

let local = moment.utc(utcTime,'HH:mm').local().format("hh:mm A");

let localTime = local;//setting local time
let utc = moment(localTime,'hh:mm A').utc().format("HH:mm");

$("#utc").html(utcText + " (UTC Time)");
$("#local").html(local + " (Local Time)");
$("#utc1").html(localTime + " (Local Time1)");
$("#local1").html(utc + " (UTC Time1)");
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.19.2/moment.js"></script>
<div id="utc"></div>
<div id="local"></div>
<div id="utc1"></div>
<div id="local1"></div>

Create a moment object using time and type , then convert to local timezone using local()

发布评论

评论列表(0)

  1. 暂无评论