2017-08-08 162 views
0

我想将UTC时间转换为客户端浏览器时区。如何将UTC时间转换为浏览器本地时区?

我使用下面的代码

var utcDate = '08-Aug-17 10:12:29 AM' + ' UTC'; 
var date = new Date(utcDate); 

输出:Tue Aug 08 2017 15:42:29 GMT+0530 (India Standard Time)

预期输出:08-Aug-2017 3:42 PM

如何设置格式在JavaScript中的日期?

回答

1

function formatDate(date) { 
 
     var monthNames = [ 
 
     "Jan", "Feb", "Mar", 
 
     "Apr", "May", "Jun", "Jul", 
 
     "Aug", "Sep", "Oct", 
 
     "Novr", "Dec" 
 
     ]; 
 

 
     var day = date.getDate(); 
 
     var monthIndex = date.getMonth(); 
 
     var year = date.getFullYear(); 
 
     var tim = date.getHours() + ":" 
 
           +date.getMinutes(); 
 
    function tConvert (time) { 
 
    time = time.toString().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) 
 
    if (time.length > 1) 
 
    { 
 
     time = time.slice (1); 
 
     time[5] = +time[0] < 12 ? 'AM' : 'PM'; 
 
     time[0] = +time[0] % 12 || 12; 
 
    } 
 
    return time.join (''); // return adjusted time or original string 
 
} 
 
    return day + ' ' + monthNames[monthIndex] + ' ' + year +' '+tConvert (tim); ; 
 
    } 
 

 
    console.log(formatDate(new Date())); // show current date-time in console

+0

输出“82017年8月16日7:'我想输出: - 2017年8月8日4:7 PM – ABB

+0

现在试试看@AshutoshBodake – Nithin

+0

完美地工作@Nithin – ABB

0

您可以在应用程序中使用时间库来处理很多日期时间相关的问题。

moment.utc('Your UTC time here').locale("your culture here").format('llll') 

Download momentJs here

1

对于这一点,你必须通过以下方式来使用momentJS
使用momentJS你可以做到这一点

var utcDate = '08-Aug-17 10:12:29 AM' + ' UTC'; 
console.log(moment(utcDate).format('DD-MMM-YYYY hh:mm:ss a')); 
相关问题