How do I create a moment object with just the time and not the date?

11,981

Neither moment.js nor JavaScript have a time-of-day type. You can fake it by using an arbitrary day (e.g. 1970/01/01) for all of your time-of-day objects.

moment("1970-01-01 16:00Z")

EDIT:

var time = "16:00"
var day = moment().tz('GMT');
var splitTime = time.split(/:/)
day.hours(time[0]).minutes(time[1]).seconds(0).milliseconds(0);

EDIT 2020:

var time = "16:00"
var day = moment().zone('GMT');
var splitTime = time.split(/:/)
day.hours(parseInt(splitTime[0])).minutes(parseInt(splitTime[1])).seconds(0).milliseconds(0);
Share:
11,981
user1261710
Author by

user1261710

Updated on June 26, 2022

Comments

  • user1261710
    user1261710 almost 2 years

    Here is what I am trying to do.

    I want to have a moment object with timezone GMT @16:00.

    If this time is in the past then +1d and if it is in the future it will be the same day.

    How do I do this and how do I set the time to 16:00 after I create the object?

    This doesn't work:

    var day = moment('16:00','HH:mm').tz('GMT');
    

    If I make a new moment object how do I set the time after?

    var day = moment.tz('GMT');
    

    There is nothing like this day.set(16:00, 'time of day'):

    Is there?

    --- edits:

    How can I set the time of day after Ii create it? If I go moment().tz(GMT) then it will be the current time in that zone. How can I change the time of day after that?

    Also, how can I change the date of that object?


    I have a string with the time. I want to parse this and put it into my moment object that I made above. What's the best way to do it?

    var time = "16:00";
    
    var day = moment().tz('GMT');
    

    How to set the day time from the string?