Reputation: 1381
I am using bs-datepicker for save time as number in mongodb. In mongodb, it has time field with value i.e, 38700000
and 41400000
which are 16.15
and 17.00
respectively.
Now, i want to format the above time in readable form. I am using moment 2.16
. Here i try but unable to do jsfiddle
console.log(moment.unix(38700000).format('HH:mm')) //03:30, expect:16:15
console.log(moment.unix(41400000).format('HH:mm')) //09:30, expect:17:00
And, how to convert from HH:mm to number. e.g 18:71
convert into number
Upvotes: 3
Views: 8729
Reputation: 241485
The data you have is in terms of milliseconds since 1970-01-01 00:00:00.000 UTC.
38700000 == 1970-01-01T10:45:00Z
41400000 == 1970-01-01T11:30:00Z
If you convert those to the time zone offset you mentioned in comments (UTC+05:30) then the time portion of the values line up to what you expected.
38700000 == 1970-01-01T10:45:00Z == 1970-01-01T16:15:00+05:30
41400000 == 1970-01-01T11:30:00Z == 1970-01-01T17:00:00+05:30
Your values don't align at all, because you are using moment's unix
function, which expects time in seconds, not milliseconds (because Unix Time is in whole seconds unless otherwise specified).
Also, by relying on the local time zone, you may get different values than expected if the user is in a different time zone.
The correct way to get what you asked for is:
moment(38700000).utcOffset("+05:30").format("HH:mm") // "16:15"
moment(41400000).utcOffset("+05:30").format("HH:mm") // "17:00"
Do recognize though that this means your original data is not stored with reference to UTC, but with reference to UTC+05:30. It would be better if you had stored UTC-based values instead, so you would do:
moment.utc(58500000).format("HH:mm") // "16:15"
moment.utc(61200000).format("HH:mm") // "17:00"
Of course, the real problem here is that you're storing a time-of-day into a date-time field. Probably the best thing to do would to not use the Date
type at all in your MongoDB data, but rather just store the string "16:15"
or the equivalent number of total minutes as an integer (60 * 16 + 15 == 975).
Upvotes: 4