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

Can anyone offer me advice on troubleshooting a failed Capifony deployment caused by a time out during the assetic:dump process?

$ cap deploy Unfortunately, the deployment process is failing and I am receiving the following error message: * executing "cd /var/www/site/prod/releases/20120831164520 && php app/console assetic:dump web --env=prod --no-debug" servers: ["site ...

Exploring JSON data to extract values

I am facing difficulty parsing a complex array of JSON, specifically extracting the values "1238630400000" and "16.10". I need to extract all values from this JSON but I am unsure how to do it. Here is the code I have attempted so far: for (var key in my ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Creating a new music application and looking for ways to keep track of and update the number of plays for

I'm currently developing a music app and am looking for a way to update the play count every time a user listens to a song for at least 30 seconds. I've attempted the following approach: let current_final; let current_initial; ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

What is a reliable method for consistently updating backend C# with user-side JS data whenever it is altered?

I'm working on a front end JS application that includes visual sliders. I need to send the updated slider information to the C# backend (ASP.NET) whenever a user makes changes. After some research, it seems like AJAX is the most efficient way to achie ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

Successful Ajax request made within a loop to update a global variable

I am trying to set a global variable from a function and loop through AJAX calls to get the distance. However, I'm facing an issue where the nearestIndex variable always ends up being undefined. The first solution I came across was to use async: fals ...

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

"Changing the name of a symbol that is automatically imported from an internal library in

Within my module, I find myself using the Element class that is implicitly imported from the "dom" internal library. However, I also need to create my custom Element class within the same module. This presents a problem due to the name collision and poten ...

Ways to show text in a password field

I'm looking to have the password field on a page. I'd like to show the text "Enter password" on the screen before the user starts entering their password, but once they focus on the field to enter their password, it should switch back to password ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

Why does socket.io have trouble connecting when clients are using different IP addresses on separate wifi networks?

I've encountered an issue where socket.io won't connect when clients are on different wifi networks (ip address) using my self-configured Ubuntu Nginx server. Strangely enough, it works perfectly fine on a pre-configured Heroku server. Here is a ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

Encountering a Peer dependency problem while executing node within a docker environment

Currently, I am utilizing `node-pg-migrate`, which has a peer dependency on `pg`. Here is an excerpt from the library's `package.json` file: "peerDependencies": { "pg": "^4.3.0" }, My attempt to execute the application in Docker involves the fo ...

Unveil the power of the "Enter" key with these jQuery hacks

Is there a way to prevent the Enter key from being counted as a character when disabling the submit button until something is entered in a TextArea? This functionality is achieved using the Count.js.coffee script. $(document).ready -> $(".cmnt_btn") ...