Get rid of the seconds in the output of the toLocaleTimeString

The method

Date.prototype.toLocaleTimeString()
provides a language-sensitive representation of the time part of a date in modern browsers.

Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows the time in formats like hh:mm:ss or hh:mm AM/PM.

second: Specifies how the second should be displayed. Options include "numeric" and "2-digit".

Source: MDN reference

This means that you cannot simply use something like {second: false}.


I am seeking a simple yet effective way to exclude the seconds from a time string formatted as hh:mm:ss.

var date = new Date();
var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
console.log(time); // 15:24:07

The following regular expressions do not achieve the desired outcome:

time.replace(/:\d\d( |$)/,'');
time.replace(/(\d{2}:\d{2})(?::\d{2})?(?:am|pm)?/);

Answer №1

The following code snippet can be used to extract the time:

let currentTime = new Date().toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'})
           .replace(/(:\d{2}| [AP]M)$/, "");

Interestingly, Google Chrome displays the time differently:

new Date().toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});

It returns "12:40 PM"

Answer №2

Here is another approach to achieving the same result:

const time = (new Date()).toLocaleTimeString();
const formattedTime = time.match(/\d{2}:\d{2}|[AMP]+/g).join(' ');
console.log(formattedTime);

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

Vue.js filters items based on their property being less than or equal to the input value

I'm currently working on a project in vue.js where I need to filter elements of an object based on a specific condition. I want to only return items where maxPeoples are greater than or equal to the input value. Below is a snippet of my code: model ...

Ways to display the hidden element using AngularJS

I want to show the information of "[6] Peter who is 95 years old" in a hidden text box, which should only appear when the button <button ng-click="show_id(friend.id)">get my id</button> is clicked. The name should be displayed using the ng-mode ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Issue with Node.js and Express redirect not directing to intended URL

Utilizing the nodejs/express view engine in my application allows me to render an assigned template onto the screen when the route points to an existent URL. Previously, I had set up a redirect to the homepage for any user typing in an unexisting URL. Howe ...

Displaying images dynamically in Angular using ng-repeat with URL strings

I'm working on a project where I need to dynamically call pictures inside an ng-repeat loop. Initially, I tried adding a key/value pair of 'img' to the JSON object I'm fetching and then dropping it inside the URL. However, this approach ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

Encountering HTML content error when attempting to log in with REST API through Express on Postman

I'm currently in the process of developing a basic login API using Node.js and Express. However, I've encountered an error when testing with Postman: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

How to remove elements from a JavaScript array: exploring the potential use of the delete function in JavaScript

I'm currently using Flot JS charts and I am attempting to completely remove a specific plot series from my data array either through jquery or plain javascript. Below is an example of what my data array consists of: [ { "label" : "Citrix PV Ether ...

Displaying a blank column in a table using JavaScript

I am trying to write a JavaScript function that will add a new column to a table. I want this new column to be displayed at the index where it is added, and then hidden once the addition is complete. Here is the code for my method: function addColumnToTa ...

Error in Node.js: Trying to access property 'get' of an undefined object

Although I have some knowledge of JavaScript, I am new to Node.js. Despite it being a common issue, I am having trouble identifying the source of the error because my debugging skills in Node.js are lacking. Here is my app.js: var index = require('. ...

props remain undefined even after being assigned in the redux store

I encountered an unusual error related to a reducer called prs when adding or deleting a person in an app. Essentially, this app allows users to add or remove a person with a unique ID assigned to each individual. To start off, here is the parent componen ...

Archive a webpage with refreshed content using ajax

Is there a way to save a webpage that has been updated through an ajax request? I'm looking to preserve basecamp message threads, but exporting is not possible since I am not the account owner. When attempting to use the javascript command below: jav ...

Error: The function $(...) that is being called is not recognized as a dialog function

My website has been giving me headaches as I try to integrate a basic CMS. Despite three full days of work, I am still facing one persistent problem! I have exhausted all my known methods, researched some solutions, but none seem to work. In order to iden ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

Experiencing Excessive Recursion While Dynamically Attaching Click Event Listener With Post Method to a Div Element

I'm encountering 'too much recursion' errors when trying to dynamically add a click handler to specific div tags with the class name 'reportLink'. Despite successfully logging the innerText of the divs, the code fails when attempti ...

Video background in webflow not currently randomizing

I want to add a dynamic video background to my website created with Webflow. I attempted to achieve this using Javascript by including the following links: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70fed ...

AngularJS: Changing color property using toggle when a CSS class is modified

After starting to learn AngularJS, I have been able to find many helpful answers on this forum. However, there is one particular issue that has been causing me frustration. My goal is to dynamically change the color property of an element only when it has ...

Next.js Content Switching: A Step-by-Step Guide

On my app, I have a main dashboard featuring a sidebar navigation and content container. However, being new to next.js and its routing system, I'm unsure how to update the content when a user navigates using the sidebar. Do I need to create separate p ...