Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding?

For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09?

Answer №1

In the world of Swift programming, JSON encoding by default presents a value representing the number of seconds elapsed since ReferenceDate. If you'd like to delve deeper into this concept, check out: https://developer.apple.com/documentation/foundation/jsonencoder/2895363-dateencodingstrategy

Interestingly enough, it appears that ReferenceDate refers to 00:00:00 UTC on 1 January 2001. For more insights, take a look at: https://developer.apple.com/documentation/foundation/nsdate/1409769-init

If you want to convert a date to its corresponding Swift time interval, here's a handy function:
function dateToSwiftInterval(date: Date): number {
    const referenceDate = Date.UTC(2001,0,1);
    const timeSpanMs = (date - referenceDate);
    return timeSpanMs / 1000;
}
To put this concept into practice, consider the following example with myDate initialized as new Date(1598366769000):
const myDate = new Date(1598366769000);
console.log(dateToSwiftValue(myDate)); // 620102769

Answer №2

In Elwyn's explanation, Swift interprets dates as intervals of time that are measured in seconds since 1 Jan 2001 UTC. On the other hand, Javascript Dates measure time in milliseconds since 1 Jan 1970 UTC. To convert between the two, you just need to account for the difference in reference dates and adjust accordingly.

// Here's a Javascript function to convert a Date to a Swift time interval
// The input parameter 'date' is a Javascript Date object (defaults to current date and time)
function toSwiftTI(date = new Date()) {
  return (date - Date.UTC(2001,0,1)) / 1000;
}

console.log(toSwiftTI());

Since the time difference remains constant at 978307200000, you may choose to use this value directly instead of recalculating it each time:

return (date - 978307200000) / 1000;

To go from a Swift time interval back to a date, simply multiply by 1,000 and add the constant:

function swiftToDate(ti) {
  return new Date(ti * 1000 + 978307200000);
}

console.log(swiftToDate(620102769.132999).toISOString());

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

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Mastering the Art of Tab Selection with Jquery

I am trying to implement a tabs control using jQuery. Here is the HTML code I have: <div id="tabs" class="news1"> <ul> <li><a href="#tabs-1">Track</a></li> <li><a href="#tabs-2">History&l ...

Problems arising from the implementation of CSS modules in React applications

As a beginner in React, I recently started learning how to utilize CSS modules within my React projects. However, I encountered an error that read: Failed to compile. ./src/components/Header/Header.js Module not found: Can't resolve './Header.mo ...

What is the process for obtaining a flattened tuple type from a tuple comprised of nested tuples?

Suppose I have a tuple comprised of additional tuples: type Data = [[3,5,7], [4,9], [0,1,10,9]]; I am looking to develop a utility type called Merge<T> in such a way that Merge<Data> outputs: type MergedData = Merge<Data>; // type Merged ...

Key-based user retrieval is unavailable in Express, "findAll" can only be done through email

I've created a straightforward Express/Pug application designed for searching users in a database by "email" or by "key". In this setup, each user is assigned a unique string as their key. The structure of my user model and index model files can be se ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

Checking for identical inputs in a React component's onChange event: how can it be done?

I'm currently working on implementing an onChange event in React to validate if two input fields are identical, specifically for confirming a password. The goal is to display a message below the input fields as users type, indicating whether the passw ...

What is causing onbeforeunload to consistently display a dialog box?

I'm facing an issue where my javascript code displays a confirmation dialog even when there is no unsaved data. I have simplified the problem to this bare minimum: window.addEventListener("beforeunload", (e) => { e.returnValue = null; retu ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

Executing functions in a pre-defined order with AngularJS: A step-by-step guide

In my AngularJS Controller, I have a receiver set up like this: // Broadcast Receiver $rootScope.$on('setPlayListEvent', function(event, playListData) { if($scope.someSoundsArePlaying === true) { $scope.stopAllS ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

innovative jquery table creator

I have created a basic dynamic HTML table generator using jQuery, see below... <button id="addcolumn">Add Column</button> <button id="addrow">Add Row</button> <table width="100%" border="1" cellpadding="0" cellspacing="0"> ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

Ways to prompt a window resize event using pure javascript

I am attempting to simulate a resize event using vanilla JavaScript for testing purposes, but it seems that modern browsers prevent the triggering of the event with window.resizeTo() and window.resizeBy(). I also tried using jQuery $(window).trigger(' ...

How to retrieve the value instead of the key/ID in a Laravel controller?

I am extracting data from the database and displaying it on the invoice view page using the json_encode($items); function. When I try to insert the 'price' field into the database, only the id/key is being stored instead of the actual value. Any ...