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.

wobsoriano
  • 12,348
  • 24
  • 92
  • 162
  • And you're not capable to read the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)? – Teemu Sep 14 '17 at 06:17
  • See this [answer](https://stackoverflow.com/a/9151985/7479709). – ehmprah Sep 14 '17 at 06:18

3 Answers3

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>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
1

You should be able to use momentJS custom parsing:

moment("2:12 PM", "H:mm A");
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
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.

Shivam Sharma
  • 1,277
  • 15
  • 31