2017-04-19 143 views
0

請將此「15:00」作爲字符串發送給我。將節點js中的字符串「15:00」轉換爲時間格式「下午3:00」

我想將它轉換爲下午3點;意味着我想將它從GMT轉換爲EST。

請告訴我如何通過內置功能或創建一些自己的功能?

+2

的可能的複製[如何使用的時區偏移的NodeJS?](http://stackoverflow.com/questions/10615828 /如何使用時區偏移量在nodejs) –

+3

格林威治標準時間到美國東部時間不是15:00至下午3:00,這只是24小時至12小時的表示 - 所以你需要什麼?時區或顯示格式的轉換?如果是後者,請在這裏查看:https://www.google.com/search?q =轉換+ 24小時+到+ 12 +小時+ javascript – mplungjan

回答

0

我寫這可能滿足您的需求函數:

function convertTime(time){ 
    var arr = time.split(':'); //splits the string 
    var hours = Number(arr[0]); 
    var minutes = Number(arr[1]); 
    var AMPM = ""; 
    if(hours>=12 && hours != 24){ //checks if time is after 12 pm and isn't midnight 
    hours = hours-12; 
    AMPM = " pm"; 
    }else if(hours<12){//checks if time is before 12 pm 
    AMPM = " am"; 
    } 

    if(hours==24){//special case if it is midnight with 24 
    hours = hours - 12; 
    AMPM = " am" 
    } 

    if(hours==0){//special case if it is midnight with 0 
    hours = hours + 12; 
    } 

    //converts the Numbers back to a string 
    var sHours = hours.toString(); 
    var sMinutes = minutes.toString(); 
    if(hours<10){//checks if the hours is 2 places long and adds a 0 if true 
    sHours = "0" + sHours; 
    } 
    if(minutes<10){//checks if the minutes is 2 places long and adds a 0 if true 
    sMinutes = "0" + sMinutes; 
    } 

    var result = sHours + ":" + sMinutes + AMPM; //sets string back together 
     return result; 
} 

https://jsfiddle.net/b059upu8/

相關問題