How to parse time string without offset using moment.js?

by arnoldo.moen , in category: Javascript , 5 months ago

How to parse time string without offset using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 3 months ago

@arnoldo.moen 

To parse a time string without an offset using moment.js, you can use the moment.utc() function and set the desired time value. Here's an example:

1
2
3
4
5
6
7
8
9
const moment = require('moment');

const timeString = '12:30';

// Parse the time string without offset using moment.utc()
const parsedTime = moment.utc(timeString, 'HH:mm');

// Use the parsed time
console.log(parsedTime.format('HH:mm'));


In this example, the timeString is in the format '12:30' (24-hour format). The moment.utc() function is used to parse the time string without taking into account any time zone offset. The string format 'HH:mm' specifies that the time string is in the 'HH:mm' format (hours:minutes).


By default, moment.js will parse the time string using the current system's time zone. Using moment.utc() ensures that the parsed time is treated as UTC time. The parsedTime object can then be used for further manipulations or formatting.


In the example, parsedTime.format('HH:mm') is used to format the parsed time back to a string representation in the 'HH:mm' format.