0

Let's say I have 2:12 PM as my time from an input, and I want to convert it to a timestamp combined with the current date.

I can get the current timestamp using Date.now() but my problem is I want the time to be based on the input.

If moment can be used, then better. Any help would be much appreciated.

2
  • And you're not capable to read the documentation? Commented Sep 14, 2017 at 6:17
  • See this answer. Commented Sep 14, 2017 at 6:18

3 Answers 3

2

You could pass in the time format to moment's constructor, along with the input's value as string to parse it into a moment object. Like this:

console.log(moment('2:12 PM',"hh:mm a").format('lll'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

1

You should be able to use momentJS custom parsing:

moment("2:12 PM", "H:mm A");

Comments

1

Using simple JavaScript

  1. Take date

    var d = new Date();
    
  2. Split it

    var l = d.toString().split(":");
    
  3. Slice it

    var f =l[0].slice(0,-2);
    
  4. Get your time variable

    var ty="11:22:00";
    
  5. Create Date

    var j = new Date(f + ty);
    

Done, It's in j


One line solution:

var d = new Date();
var ty = "11:22:00";
var newDate = new Date(d.toString().split(":")[0].slice(0,-2) + ty);

It's the full date, you can use and change it as you like.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.