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

Manage and update events in the Angular Bootstrap Calendar

For the past few days, I have been working on integrating a calendar into my project. I decided to repurpose an example provided by the developer. One issue that I've come across is related to the functionality of deleting events when using the dropdo ...

Passing the value of the attribute from event.target as a parameter in a knockout click event

I have been exploring knockout events and am currently working on a functionality involving three buttons ("Packers", "Trail Blazers", and "Dodgers") within a div. Each button is associated with a data-league attribute of "NFL", "NBA", and "MLB," respectiv ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

What is the best method for rounding a decimal number to two decimal places?

Here is the JavaScript code I am using: $("input[name='AuthorizedAmount'], input[name='LessLaborToDate']").change(function () { var sum = parseFloat($("input[name='AuthorizedAmount']").val()).toFixed( ...

Generating JSON data from a dropdown menu element

I'm working on a web page that showcases information for students in my database. One key field is their birth country, currently stored as the full name of the country. My goal is to convert these full country names into two-character strings. For ex ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

JavaScript: The delayed submission feature is malfunctioning

Visit this link When using JSFiddle, a strange list of errors is generated (see pic here). However, the auto-submit feature on my page works fine, but it lacks the specified delay. Thank you in advance for any assistance. <form id='formBlokUziv&a ...

Incorporating Chip into a Material-UI DataGrid column

I'm having trouble displaying data of a specific column inside a chip. I attempted to use the Chip component in my code: StackBlitz Demo Web Link: Live Demo I tried to incorporate it using: import Chip from '@mui/material/Chip'; but c ...

Encounter a problem while running `ng build` due to a module not

I was looking to automate the building of my Angular project on a separate CentOS 7 machine. Here are the versions being used: Angular CLI: 8.3.23 Node: 13.14.0 OS: linux x64 Angular: 8.2.14 ... animations, common, compiler, compiler-cli, core, forms ... ...

The responseXML received from an Ajax/POST request is missing only when using Chrome browser

While working on a "simple" JavaScript application, I noticed an unusual behavior. A function in the script sends a request with parameters to a .php page using the traditional Ajax/POST method. function sendRequest(params, doAsync, onSending, onDone) { v ...

The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is ...

Is there a way I can retrieve my Nodemailer email and store it in a variable?

I am currently utilizing the nodemailer module in conjunction with node.js and have successfully implemented the following: let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<a href="/cdn-cgi/l/email ...

Using Laravel and vue.js to convert values into an array

I am currently utilizing vue.js within my Laravel project. Within the project, I have three tables: Article Location article_location (pivot table) I am looking to convert location articles into JSON format so that I can pass it to vue. How should I ...

Incorporate a cookie within a jQuery dialog box and display the chosen value on the webpage following submission, alongside

I am creating a webpage where users are required to input their postcode in order to search for factories nearby. To achieve this, I have implemented a jQuery modal dialog that prompts users to enter their postcode and click submit. Once submitted, a cook ...

The information does not display in the AngularJS-generated table

Struggling with AngularJS directives? Let's take a look at the code: <div ng-controller="Controller"> <table> <thead> ....... </thead> <tfoot> ....... </tfoot> <tbody> < ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...