0

I have a unix timestamp which is set to 12:00:00 AM (i.e. midnight at the start of the day). I want to add to this a time in the day, such as 5pm, and get a new unix timestamp.

The unix timestamp is passed to me from a database as a string, as is the time in the day.

What I am looking for is something like this:

let newUnixTimestamp = moment(unixTimestampForStartOfToday + "5pm");
Bill Noble
  • 6,466
  • 19
  • 74
  • 133
  • Can you not try something like `(parseInt(timeInDay) + timeInDay.indexOf('pm') > 0 ? 12: 0)` – Rajesh Oct 16 '17 at 09:39
  • Sorry Rajesh I do not understand how that fits in with what I am trying to achieve. – Bill Noble Oct 16 '17 at 09:41
  • If I understand correct, you wish to create a string with time value added to date value and then create date object using moment. Correct? – Rajesh Oct 16 '17 at 09:44
  • I am trying to take a unix timestamp, add a time in the day (e.g. 5pm), and end up with a unix timestamp for the correct time of day. – Bill Noble Oct 16 '17 at 09:46

2 Answers2

1
var duration = moment('5:30pm', ['ha', 'h:mma']);
moment.unix(unixTimestampForStartOfToday).add(duration.hours(), 'h').add(duration.minutes(), 'm');
davidchoo12
  • 1,261
  • 15
  • 26
  • My unixTimestampForStartOfToday is 1483920000 which is equivalent to Monday 9th January 2017 12:00:00 AM. Using this with your code gives me 1545120000 which is equivalent to Tuesday 18th December 2018 08:00:00 AM. Am I not using your code correctly? – Bill Noble Oct 16 '17 at 09:57
  • I forgot to add `.unix` on it. Updated my answer, give it a try. – davidchoo12 Oct 16 '17 at 10:02
  • That did it for 5pm and 4am thanks. Is there a way to handle part hours like "5:30pm" and "4:05am"? – Bill Noble Oct 16 '17 at 10:08
  • You can change the `moment('5pm', 'ha')` to `moment('5:30pm', 'h:mma')`. Check out the hours, minutes [formatting tokens](https://momentjs.com/docs/#/parsing/string-format/) – davidchoo12 Oct 16 '17 at 10:12
  • Thanks. That still gives me the 5am time and not 5:30am. My code is this: moment.unix(ninethJan2017).add(moment('5:30am', 'h:mma').hours(), 'hours'); – Bill Noble Oct 16 '17 at 10:18
  • Updated answer, try it out – davidchoo12 Oct 16 '17 at 10:32
  • Excellent! That works perfectly. Thanks so much for your help, – Bill Noble Oct 16 '17 at 10:39
0

You can refer to the documentation for a list of operations you can perform. but for this case, you can do something like this

moment(unixTimestampForStartOfToday).add(17, 'hours')

that should set the time to 5pm of that date

Maru
  • 590
  • 5
  • 14
  • What I am wanting to do, if possible, is use the time of day string that I have (e.g. "5pm") in the moment call without having to parse with additional code. – Bill Noble Oct 16 '17 at 09:48
  • davidchoo's answer below would work if you want minimal changes to your time string, thats the only way to manipulate date objects using momentjs that doesnt involve string manipulation of the input – Maru Oct 16 '17 at 09:52