extract time from datetime using javascript

前端 未结 8 875
忘掉有多难
忘掉有多难 2020-11-29 07:08

how can i extract time from datetime format.

my datetime format is given below.

var datetime =2000-01-01 01:00:00 UTC;

I only want

相关标签:
8条回答
  • 2020-11-29 07:51
    var datetime = ("2000-01-01 01:00:00 UTC");
    var d1 = new Date(datetime);
    var minute = d1.getUTCMinutes();
    var hour = d1.getUTCHours();
    if(minute > 0)  
         alert(hour+"."+minute);
    else
         alert(hour);
    

    Demo

    0 讨论(0)
  • 2020-11-29 07:53

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

    Date.prototype.toLocaleTimeString() Returns a string with a locality sensitive representation of the time portion of this date based on system settings.

    var time = datetime.toLocaleTimeString();
    

    Update:

    The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

    // Depending on timezone, your results will vary
    var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
    
    console.log(event.toLocaleTimeString('en-US'));
    // expected output: 1:15:30 AM
    
    console.log(event.toLocaleTimeString('it-IT'));
    // expected output: 01:15:30
    
    0 讨论(0)
  • 2020-11-29 07:54

    Use the following code:

    var datetime = "2000-01-01 01:00:00 UTC";
    
    var dt = new Date(datetime);
    var hr = dt.getUTCHours();
    if(hr > 12) {
       hr -= 12;
    }
    alert(hr);
    

    refer this link also.

    0 讨论(0)
  • 2020-11-29 08:01

    Assuming you have a Date object like

    var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
    // or
    var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
    

    then use the getUTCHours method:

    datetime.getUTCHours(); // 1
    
    0 讨论(0)
  • 2020-11-29 08:06

    What about these methods

    new Date().getHours()

    new Date().getMinutes()

    For example:

     var d = new Date();
     var n = d.getHours();
    

    Edited

    Return the hour, according to universal time:

    new Date().getUTCHours()

    Example:

    var d = new Date();
    var n = d.getUTCHours(); 
    
    0 讨论(0)
  • 2020-11-29 08:10

    As an alternative if you want to get the time from a string -

    var datetime ="2000-01-01 01:00:00 UTC";
    var myTime = datetime.substr(11, 2);
    alert(myTime) //01
    
    0 讨论(0)
提交回复
热议问题