dev
dev

Reputation: 916

convert the time using date-fns

Using datefns how can i convert the below format to the expected one

const input = "3:0:0:0"

const output: "3am"

What i have tried.

import format from 'date-fns/format'

const input = "3:0:0:0"
const output = format(input, "HH:MM:SS:NS")

console.log(output) // getting invalid date.

https://codesandbox.io/s/date-fns-forked-w4c7o

Upvotes: 0

Views: 2951

Answers (1)

mplungjan
mplungjan

Reputation: 177691

Without this library I would use vanilla JS and

const fmtTime = str => {
  let [hh,mm,ss,ms] = str.split(':')
  return `${hh}${+mm>0?`:${mm}`:''}${hh>12?'pm':'am'}`
};
const input1 = "3:30:0:0";
const input2 = "3:0:0:0";

console.log(fmtTime(input1))
console.log(fmtTime(input2))

Upvotes: 2

Related Questions