Home > Mobile >  Day.js support for JSON formatted Timespan parsing (e.g. 14.06:10:36)
Day.js support for JSON formatted Timespan parsing (e.g. 14.06:10:36)

Time:04-12

I was using Moment.js until now to parse JSON formatted time spans from a REST API. The time span in the JSON response is formatted in the very common "dd.hh:mm:ss" (e.g. "14.06:10:36" for 14 days, 6 hours, 10 minutes and 36 seconds) format.

Moment.js has an easy way of parsing it, but to my surprise I could not find a way to parse those time span string with day.js. For most purposes day.js is a great replacement for moment.js, which is in maintenance mode now and also has a much larger memory footprint.

Is there anything I missed, or is there a way to parse time span strings with day.js?

CodePudding user response:

There is a duration plugin. That might be what you are looking for.

CodePudding user response:

You're looking for Dayjs durations. You'll probably wanna use regex to parse it first.

import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";

dayjs.extend(duration);

const str = "14.06:10:36";

const groups = str.match(/(\d{2})\.(\d{2}):(\d{2}):(\d{2})/);


const dayjsDuration = dayjs.duration({
  days: parseInt(groups[1]!),
  hours: parseInt(groups[2]!),
  minutes: parseInt(groups[3]!),
  seconds: parseInt(groups[4]!)
})
  • Related