Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code:

var newDate = new Date(timeFromat);
timeFormat = newDate.toLocaleString();

Now, I want to change the time format to a 24-hour clock format like this: 12/16/2011 15:49:37 and I need to accomplish this in JavaScript.

This is what I have tried so far:

var firstPartOftimeFormat = timeFormat.substring(0,9);
var secondPartOftimeFormat = timeFormat.substring(10,20);

However, this method doesn't work properly when the date format is different, such as: 3/16/2011. The following part of the code seems to be effective though.

var time = $("#starttime").val();
var hours = Number(secondPartOftimeFormat.match(/^(\d+)/)[1]);
var minutes = Number(secondPartOftimeFormat.match(/:(\d+)/)[1]);
var AMPM = secondPartOftimeFormat.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

Do you have any alternative suggestions or approaches to achieve this? Your help would be greatly appreciated. Thank you.

Answer №1

try using the

dateObj.toLocaleString([locales[, options]])
method

Method 1 - Utilizing locales

let currentDate = new Date();
console.log(currentDate.toLocaleString('en-CA'));

Method 2 - Applying options

let customOptions = { hour12: false };
console.log(currentDate.toLocaleString('en-US', customOptions));

Answer №2

hourCycle: 'h23' is Fantastic

Kudos to

new Date().toLocaleString('ru-RU', {
    timeZone: 'Europe/Moscow',
    hourCycle: 'h23',
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
});

Answer №3

Utilizing some helpful resources:
Date/toLocaleDateStringMDN
Date/toLocaleTimeStringMDN

const lang = navigator.language || navigator.languages[0];
const date = new Date();
const date_locale = date.toLocaleDateString(lang, {
  day: 'numeric',
  month: 'short',
  year: 'numeric'
});
const time_locale = date.toLocaleTimeString(lang);

const formatted = `${date_locale} ${time_locale}`;
console.log(formatted)

We determine the current language by accessing the Navigator object in the Window.
If lang is undefined, default settings will be applied.

To specify a particular format, you can manually set lang to options like: 'en-US', 'eu', 'en-GB', 'de-DE', 'hr-HR', and more.

Here's an instance for changing the time:

const date = new Date();
console.log(date.toLocaleTimeString('en-US')) // 12-hour clock
console.log(date.toLocaleTimeString('en-GB')) // 24-hour clock
console.log(date.toLocaleTimeString())        // Default

Answer №4

Instructions to obtain the 24-hour format:

let currentDate = new Date();
console.log(currentDate.toLocaleTimeString([], {
    hourCycle: 'h23',
    hour: '2-digit',
    minute: '2-digit'
}));

Answer №5

To obtain the time in 24-hour format, you can utilize the code snippet provided below:

const date = new Date("9/20/2021 10:30:15 AM");
console.log(date.getHours()); // Output will be 10
console.log(date.getMinutes()); // Output will be 30

Answer №6

const time = new Date().toLocaleTimeString('fa-IR', { hour12: false, hour: '2-digit', minute: '2-digit' })

This code snippet solved the issue for me!

Answer №8

Check out this solution, it is working perfectly for me. It provides the time in a 24-hour format.

var currentDate = new Date();

var timeFormat = currentDate.toLocaleString('en-GB');

The output will be Fri Dec 14 2018 18:00:00 GMT+0530 (India Standard Time)

Answer №9

Give this a shot, it's been perfect for me. It outputs the time in a 24-hour format.

let currentTime = new Date(new Date().toLocaleString('en-GB', { timeZone: 'Europe/London' }));

Answer №10

Check this out

let currentDate = new Date();
console.log(currentDate.getHours());
console.log(currentDate.getMinutes());

Answer №11

Give this code a try!

<script type="text/javascript">
    <!--
    function showTime() {
        var currentTime = new Date();
        var currentHour = currentTime.getHours();
        var currentMinute = currentTime.getMinutes();
        var currentSecond = currentTime.getSeconds();
        document.getElementById('timeDisplay').innerHTML = 'Hour: ' + currentHour + ' Minute: ' + currentMinute + ' Second: ' + currentSecond;
    }

    window.onload = function() {
        window.setInterval('showTime()', 1000);
    }
    // -->
</script>

Answer №13

Let's convert the time format from 12-hour to 24-hour using moment.js.

Answer №14

This method was successful for me. Instead of de-DE, you can substitute in any language code such as us-GB, nl-NL, and so on.

function displayTime() {
    const currentDate = new Date();
    let currentTime = currentDate.toLocaleTimeString('de-DE', {
        hour12: false,
        hour: '2-digit',
        minute:'2-digit',
        second:'2-digit'
    });
    document.getElementById("MyClockDisplay").innerText = currentTime;
    setTimeout(displayTime, 1000);
}

displayTime();

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

Are there any limitations imposed on keydown events in JavaScript when attempting to modify the browser's

I attempted to implement a JavaScript keydown event that would refresh the page, but unfortunately, it did not function as intended. Interestingly, the same code works flawlessly when triggered by a button click event. I'm in search of a solution to r ...

What is the best way to extract the information from the checkbox in a MUI datatable?

I am struggling to transfer an array with checked values to another table in order to display only those values. How can I achieve this? I am relatively new to using react and I find it challenging to grasp how some of the functions and components work. I ...

Is there a way to retrieve the filename of a file uploaded using a shiny fileInput function?

This shiny app has a feature where users land on the 'Upload data' panel upon launching. To restrict access to the other two 'tabpanels', users must first upload both necessary files in the 'Upload data' tab. The condition for ...

"Including Span icons, glyphs, or graphs within a table cell in AngularJS based on a specified condition or numerical

I'm attempting to incorporate span icons/glyph-icons using Angular within a td before displaying the country. I've utilized the code below to achieve this, but I'm looking for a more dynamic and elegant solution. Your assistance is greatly a ...

Progress bar status displayed while uploading multiple files

I'm currently working on a Django project where I have set up a page to input data information about a file and then upload the file itself. https://i.sstatic.net/jB5cr.png Whenever the user clicks on the 'More datasets' button, it dyna ...

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...

What is the best way to incorporate multiple Bootstrap templates into an Angular project without causing conflicts between them?

When incorporating a bootstrap template into the admin interface, it is important to consider that its design may vary from the template used for visitors. Mixing multiple styles based on different templates can lead to conflicting styles and can potenti ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Issue with storage functionality in Vuex Axios response

Every time I send data to the Vuex storage using an axios response, for example: ** Sidebar.vue ** created(){ this.getRoles(); }, methods: { getRoles(){ var _this = this var roles = null this.$http.get('/api/userroles/ ...

Ways to verify that window.open is being invoked from a React component

In my React component, I have a set of nested components, each with its own checkbox. The state hook rulesToDownload starts as an empty array and dynamically adds or removes IDs based on checkbox selection. Upon clicking the 'download' button, t ...

Instructions for designing a Loading Indicator or Progress Bar within the App Directory of NextJS

Having built a substantial web application using NextJS 13, I initially utilized the Pages Router. However, as I neared completion of the website, I decided to make the switch to the App Directory. The primary motivation behind this migration was not just ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...

JavaScript Autocomplete - retrieving the value of a label

I am looking for a way to utilize the autocomplete feature in my form box to extract a specific value from the displayed label. When a user selects an option, I want to include part of the label (client_id) in the form submission process. JS: <script ...