Displaying 'hours and minutes' functions properly in all web browsers except for Safari. Utilizing JavaScript Date object

I am retrieving a date from an object within a loop in the following format: 2018-08-06 20:45:00

My objective is to only display "20:45" (always with two digits for minutes) in the client's timezone. To achieve this, I have implemented the below method in the methods section of vue.js:

ihaveadate(dateFromLoop) {
  var d = new Date(dateFromLoop);
  d.setTime(d.getTime() + new Date().getTimezoneOffset() * 60 * 1000);
  var hour = d.getUTCHours();
  var minutes = (d.getMinutes() < 10 ? "0" : "") + d.getMinutes();
  return `${hour}:${minutes}`;
}

This method worked well except for Safari where it resulted in NaN:NaN. Is there a more elegant solution to address this issue?

Based on your feedback, I have modified the implementation as follows:

var dateFromLoop = '2018-08-06 20:45:00';
var date = Date.parse(dateFromLoop.replace(" ", "T"));
const daty = new Intl.DateTimeFormat({
  hour: "numeric",
  minute: "numeric"
}).format(date);
console.log(daty);

Answer №1

Indeed, this code may not be compatible with Safari due to ECMAScript 5 ISO-8601 format support:

Another option is to use the ISO 8601 format for the date/time string. For example, you can pass and parse "2011-10-10" (just the date) or "2011-10-10T14:48:00" (date and time).

To make it work on Safari, remember to include the letter T within the date-time string:

new Date('2014-02-18T15:00:48');

You can try modifying the code like this:

new Date(dateFromLoop.replace(/\s/, 'T'));

Answer №2

If you're looking for a simple solution, consider using the moment library for all your time and date manipulation needs.

Here's an example of how you can solve your problem using Moment:

const d = new Date(yourDate);
const hourAndMin = moment().format('h:mm'); 

Check out Moment for more information!

Answer №3

If you're looking to achieve this, Vanilla is the way to go.

check out parse documentation

format details here

Here's a sample from the original source:

var date = Date.parse('2018-08-06 20:45:00'.replace(' ', 'T'));

// The output of toLocaleString without arguments varies based on implementation,
// default locale, and time zone
console.log(new Intl.DateTimeFormat({
  hour: 'numeric',
  minute: 'numeric'
}).format(date));

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

What is the best way to eliminate two identical characters along with any content in between using JavaScript?

I am trying to figure out how to remove a specific part of a string that is between matching '/' characters. For instance: '/this is/ a sentence' => ' a sentence' Although I have limited experience with regex, I am wonder ...

The disappearance of node_modules results in the failure to install any dependencies for a React application, causing an error to be thrown

I've been struggling to get a react app installed, but every time I try, I encounter the following error and the entire node_modules folder disappears. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found ...

Velocity: The initial parameter was not recognized as a property mapping

I've been experimenting with Velocity for animations (without jQuery), but I'm running into an issue where I keep getting this error message: Velocity: First argument ([object HTMLDivElement]) was not a property map, a known action, or a regis ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

How to utilize jQuery to highlight active anchor tag in an ASP.NET environment

I am attempting to modify the color of a list item when an anchor tag is clicked using jQuery. When I call a C# function from the code-behind on clicking the anchor tag, if I include "return false" in the jQuery code as shown below, the color changes but t ...

Populating a form field using another input

I am facing an issue with retrieving the price of a product in one field when the product name is selected in another field on a simple POS system. It works fine for the first product, but when I add another row for the next product, the price does not dis ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Looping through and sending multiple post requests

Is it possible to send post requests in a loop but only have the last request trigger the callback function? What am I missing here? this.assignAUnits = function(){ var currentIncidentId = this.incident.incidentId; for (var i=0; i< thi ...

Unsuccessful CORS on whateverorigin.org with YQL

Despite trying all three methods, I keep getting an error regarding cross domain access denied. Previously, I had successfully used YQL in different parts of my applications, but now it seems to have stopped working as well. JSFIDDLE <script> $(fun ...

One-liner for converting an array into an object

Is there a more concise method to convert all array indices and values into an object than the following: arr = ["one","two","three"]; var rv = {}; for (var i = 0; i < arr.length; i++) rv[i] = arr[i]; I understand that you can iterate through the ...

Tips for changing the state of a Jquery Mobile flip switch programmatically

I am encountering an issue with my jQuery Mobile flip toggle switches on my Android/iPad application. I need to be able to change their states dynamically using JavaScript. Despite trying various solutions mentioned in this thread (Change value of flip tog ...

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...

What is the best way to export image paths using require() from a single index.js file in a React Native project?

I am looking for a way to efficiently export all images from a single file named index.js, so that in the future, if I need to change the path of an image, I only have to make changes in one file. For example: export {default as avatar} from './avata ...

Vue: navigating to a specific id using scroll is malfunctioning

I have integrated the vueToScroll library to enable scrolling to a dynamically created element with a specific id. <button ref="replyBtn" v-scroll-to="{ el: '#goToReply101', duration: 800, easing: 'easi ...

Setting the iDisplayLength property in jQuery Datatables to -1 will display all rows in the table

Using jQuery Datatables, I am trying to populate a table with entries from a server via ajax. The data retrieval works perfectly, and I am able to display them in the table. However, I am facing an issue where I want to show all rows/entries at once. I hav ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. https://i.sstatic.net/5bHFO.png It displays "Sorted by ascending o ...

Using JSON.stringify() for custom serialization of an object

Imagine there is an object called a with properties: const a = { foo: 123, bar: 'example' } Now, this object is a part of another object called b like this: const b = { a: a, anotherField: "example" } While working with TypeScript, th ...

Passing a state object in a POST request body, only to find it arriving empty at the Express server

I'm having an issue with my React form component when making a POST request. The body of the request is showing up as {} even though I'm trying to send my State object. Within my form Component, I am passing the state information to another Reac ...

The route parameters in Vue SSR are being retrieved from a separate request

I am currently using Akryum/vue-cli-plugin-ssr along with vue-cli, but I have encountered an unusual issue in my Vue SSR application. It seems that the route params are getting mixed up with requests made either before or in parallel to the current one. F ...

Node.js: A Guide to Prepending a Line to a File Using the 'fs' Module

Currently, I am attempting to insert a new line at the beginning of an existing text file using node.js. Here is the code snippet I am working with: var fs = require('fs'); fs.appendFile('test.txt', 'X Y', function (e ...