ufk
ufk

Reputation: 32114

format a full date with timezone and day of the week name string

I'm trying to create a date object from the string 01:03:55.065 GMT Tue Mar 16 2021 in NodeJS javascript with date-fns v2.21.3 but I wouldn't mind using regular javascript Date instead.

this is my code:

const df = require('date-fns');

const setupTime = '01:03:55.065 GMT Tue Mar 16 2021';
const ret = df.parse(setupTime,'HH:mm:ss.SSS zzz EEE dd yyyy',Date.now());
console.info(ret);

it looks like maybe format() and parse() do not have the same formatting string ?

when I try to execute this code I get:

RangeError: Format string contains an unescaped latin alphabet character `z`
    at Object.parse (/Volumes/osx-storage/projects/vocalix/parse-date-fns/node_modules/date-fns/parse/index.js:486:15)
    at Object.<anonymous> (/Volumes/osx-storage/projects/vocalix/parse-date-fns/index.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:828:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

now.. since the data that I receive will always have GMT in it, i tried to ignore the timezone and do:

const ret = df.parse(setupTime,"HH:mm:ss.SSS 'GMT' EEE dd yyyy",Date.now());

but this produces the output Invalid Date.

there is the package date-fns-tz but it doesn't include it's own format function so it's not relevant here.

any ideas how to resolve this issue?

thanks

Upvotes: 2

Views: 898

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Maybe this plain JavaScript solution will be helpful to you?

const d = "01:03:55.065 GMT Tue Mar 16 2021";

function parseDate(s){
  const a = s.split(" ");
  return new Date([a[4],a[3],a[5],a[0]+"Z"].join(" "))
}

console.log(parseDate(d));

It works with the standard date constructor, accepting a string as input.

Upvotes: 1

Related Questions