Best practices for correctly parsing a date in UTC format using the date-fns library

My log file contains timestamps in a non-ISO format:

2020-12-03 08:30:00
2020-12-03 08:40:00
...

The timestamps are in UTC, as per the log provider's documentation.

I am attempting to parse them using date-fns:

const toParse = "2020-12-03 08:40:00"
parse(toParse, 'yyyy-MM-dd HH:mm:ss', new Date()).toISOString()

Due to my computer's locale being UTC+1, I encounter this issue:

> "2020-12-03T07:40:00Z"

Instead, I expect:

> "2020-12-03T08:40:00Z".

To work around this, I currently append '+00' to parse as UTC:

const toParse = "2020-12-03 08:40:00"
parse(toParse + '+00', 'yyyy-MM-dd HH:mm:ss' + 'X', new Date()).toISOString()

This results in:

> "2020-12-03T08:40:00Z".

Is there a correct way to achieve this with date-fns? Seeking an equivalent of moment's moment.utc()

Answer №1

When it comes to handling timestamps with different offsets or timezones, you may not be concerned with what is considered "proper". Instead, you can utilize the zonedTimeToUtc function from date-fns library. This function allows you to manipulate a timestamp and adjust its offset or timezone as needed, such as converting it to UTC.

// Initial Setup
var {parse} = require('date-fns');
var {zonedTimeToUtc} = require('date-fns-tz');

// Parse a timestamp in ISO 8601 format recognized by date-fns
let location = 'UTC';
let timestamp1 = '2020-12-03 08:30:00';
let utcTimestamp = zonedTimeToUtc(timestamp1, location);

// Display the converted UTC ISO 8601 timestamp
console.log(utcTimestamp.toISOString()); // "2020-12-03T08:30:00.000Z"

// Parse a timestamp in non-standard format yyyyMMdd
let timestamp2 = '20210119';
let formatInput = 'yyyyMMdd';
let parsedDate = zonedTimeToUtc(parse(timestamp2, formatInput, new Date()), location);
console.log(parsedDate.toISOString()); // "2021-01-19T00:00:00.000Z"

You can experiment with this functionality using the code snippet on npm.runkit.com/date-fns.

Answer №2

Maybe you're searching for the parseJSON function, which can handle various date formats (although it doesn't allow you to specify the input format).

This function converts a full ISO date string in UTC time, commonly used when transmitting dates in JSON, into a JavaScript Date object.

import { parseJSON } from 'date-fns';
const utcDate = parseJSON('2020-12-03 08:40:00');

// This would give you Thu Dec 03 2020 19:40:00 GMT+1100 (Australian Eastern Daylight Time)

Answer №3

An illustration of utilizing parse and zonedTimeToUtc functions

 it('should convert Polish date to UTC', async () => {
    expect.assertions(1)
    const dateWithoutTime = '29 gru 2003'

    const parsed = parse(dateWithoutTime, 'd LLL yyyy', new Date(), {
      locale: pl,
    })

    const dateUTC = zonedTimeToUtc(parsed, 'UTC')

    expect(dateUTC.toISOString()).toStrictEqual('2003-12-29T00:00:00.000Z')
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating array objects by replacing values in Typescript

Attempted two different methods to obtain a partial summary within each array object, but unfortunately, both were unsuccessful. var arr = [ { "value": 10, "newBalance": 0 }, { "value": -10, "newBalance": 0 }, ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Maintain the tab order for elements even when they are hidden

Check out this demonstration: http://jsfiddle.net/gLq2b/ <input value="0" /> <input id="test" value="1" /> <input value="2" /> By pressing the TAB key, it will cycle through the inputs in order. If an input is hidden when focused, press ...

Here is a way to prevent a null input value from being accepted in a JavaScript function

Hey there, I have a function that looks like this: class Fun { pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) { //do something }; }; } In order for this function to work properly, I need to give it some values. For exam ...

Steps to import an external script into a NextJS application and access it from the main bundle

I have encountered an issue while working with the mercadopago library. I need to load the mercadopago script file and create an instance of the MercadoPago object. However, nextJS loads the main bundle before including the mercadopago file, resulting in a ...

Detecting the failure of chrome.extension.sendRequest

Greetings Chrome Developers! I am wondering how one can determine when a chrome.extension.sendRequest call has not been successful. I attempted the following approach with no luck: chrome.extension.sendRequest({ /* message stuff here */ }, function(req){ ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

A TypeScript object with user-defined keys

I have a question about utilizing TypeScript records with a custom Type as keys. Essentially, I have a specific type (a limited set of strings) that I want to use as keys for my record. My goal is to start with an empty initialization of this record. type ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

Error encountered while using AngularJS and Node.js with the 'phantom' node module. The application is throwing an injection error as AngularJS attempts to load a directive with a suffix

Upon loading an AngularJS page, everything proceeds smoothly with no console errors and the content displays as expected. However, encountering a different scenario where attempting to load the same page from another application using the Node module &apo ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

After entering text manually, the textarea.append() function ceases to function properly

I've encountered a puzzling issue with a tiny fiddle I created: https://jsfiddle.net/wn7aLf3o/4/ The scenario is that clicking on 'append' should add an "X" to the textarea. It functions perfectly until I manually input some text in the te ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

What causes the discrepancy between the values returned by the jQuery getter css() method and JavaScript when accessing the style variable

After recently beginning to use jquery, I decided to switch due to initialization issues when loading external styles with javascript. Here is a rule defined in an external style sheet: #siteLogoDiv { position:absolute; left:0px; top:0px; width:100%; heig ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...