Transform the ISO 8601 date format into another ISO 8601 format with the help of MomentJS

Can a date format like the following:

2003-09-25T14:00:00.000+1000 or 2003-09-25T14:00:00.000+1100

Be converted to this format?

2003-09-25T14:00:00.000Z

Using only MomentJS without any manual intervention. Additionally, I would like to understand the significance of +1000 or +1100 in this context.

Answer №1

One approach is to calculate the offset hours and add them back to the time.

var timeStrings = [
  '2003-09-25T14:00:00.000+1000',
  '2003-09-25T14:00:00.000+1100'
];

console.log(timeStrings.map(ts => {
  var m = moment(ts);
  m.add(m._tzm, 'minutes'); // Add total minute offset
  return m.toISOString();
}));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js></script>


Another method that doesn't alter the moment objects when displayed.

var timeStrings = [
  '2003-09-25T14:00:00.000+1000',
  '2003-09-25T14:00:00.000+1100'
];
var moments = timeStrings.map(ts => moment(ts));

// The moments remain unchanged when shown...
console.log(moments.map(momentDateAsUtc));

function momentDateAsUtc(m) {
  var clone = m.clone();
  clone.add(m._tzm, 'minutes'); // Add total minute offset
  return clone.toISOString();
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js></script>

Answer №2

If you're looking to show the times in UTC, it's worth noting that momentjs handles times in UTC internally. It automatically converts offset dates to UTC as it parses them :

var moments = [
  moment('2003-09-25T14:00:00.000+1000'), // 2PM in Srednekolymsk, Russia
  moment('2003-09-25T14:00:00.000+1100')  // 2PM in Sydney, Australia
]; // They are different times and not the same as 14:00:00Z
console.log(moments);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

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

Deleting a record by sending an HTTP request and then removing the corresponding object from an array in Vue.js

After successfully solving this particular issue with the help of @nils, I have encountered a new question that I hope someone can assist me with! My current situation involves having a list of records from which I can select and remove items with just on ...

What is the best way to implement transition effects while toggling between light mode and dark in tailwind 2.0?

Currently, I am working on a small project utilizing tailwindCSS and have decided to incorporate a dark mode feature. To achieve this, I created a button that toggles the dark class in the html tag. However, upon testing the functionality, I noticed that t ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

The sample Ajax XML code provided by W3Schools is ineffective

While studying xml parsing in ajax on w3schools.com, I came across an example that functioned perfectly online. However, when I saved it to my desktop as abc.html and note.xml, the XML values weren't displaying. Even though the HTML elements were vis ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Guide on implementing router-link within a select option dropdown in a Vue.js application

a.vue <template> <div>hi i am component 1</div> </template> <script> export default { name: "a", }; </script> b.vue <template> <div>hi i am component 2</div> </template> <script> ...

In react-native, when the string includes spaces, it will result in a line change

I am currently utilizing react-native in combination with styled-components. Whenever a string is typed into the text and followed by pressing the spacebar, it either results in too many line breaks or creates excessive empty spaces. An example of this i ...

spark of unique substance

Having trouble with cycle2 as all images are briefly displayed when the page loads. I tried the recommended solution http://jquery.malsup.com/cycle/faq.html but it didn't stop the flashing, indicating a different issue: The suggested fix for Cycle is ...

The pre-loader is hidden behind the block content and navigation bar

I've encountered an issue with my preloader where it's loading in front of the <body> element but not in front of the site's <navbar> or the {% block content %}. The CSS snippet to increase the z-index of the preloader is as foll ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Consolidate test outcomes from various nodes in the stack into a single graph

Nowadays, web applications consist of a variety of different technology stacks. Developers utilize languages like Ruby, Python, PHP, JavaScript, and C for the backend, as well as frameworks such as AngularJS and EmberJS for MVC/client-side code. To ensure ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Implementing delayed loading of Angular modules without relying on the route prefix

In my application, I am using lazy loading to load a module called lazy. The module is lazily loaded like this: { path:'lazy', loadChildren: './lazy/lazy.module#LazyModule' } Within the lazy module, there are several routes def ...

Development of Chrome Extensions, JavaScript dilemma

Hey there, I'm new to JavaScript and I've been diving into the world of creating Chrome extensions. I'm trying to set up a content script and browser action, but I'm struggling to get it up and running. I know I'm probably making a ...

What is the method for a HTML button to trigger the execution of a Selenium (Java) code located in a remote location through a

I need to run a Selenium Code written in Java from a NAS (Network Attached Storage) or another connected machine. My goal is to create a web page with a button that, when clicked, triggers the execution of the Selenium script located on the connected mac ...

The structure of NodeJS Express API calls revolves around handling asynchronous events

Currently, I am working on a hobby project using NodeJS and Express, but I am finding it challenging to manage asynchronous calls. There is a bug that I would like the community's help in resolving. I have set up an Express layout where I send post r ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...