Converting milliseconds into a date format

I am looking to change milliseconds into a string that displays the time duration.

function convertMsToTime(ms) {
  return ('' + Math.floor(ms / 86400000) + 'd -' + Math.floor((ms % 10) / 60).toString().padStart(2, '0'));
}

console.log(convertMsToTime(100000000));

Answer №1

const newDate = new Date(1238544816452);

newDate.toLocaleString(); // result: "5/25/2015, 1:34:06 PM"

newDate.toLocaleDateString(); // result: "7/25/2015"

newDate.toDateString();  // result: "Mon Jul 25 2015"

newDate.toTimeString(); // result: "13:35:07 GMT+0530 (India Standard Time)"

newDate.toLocaleTimeString(); // result: "1:35:07 PM"

Answer №2

If you're looking to convert a Unix timestamp to time in JavaScript, check out this snippet from: Stack Overflow. It might be just what you need.

const unixTimestamp = 1589721452;
// Create a new Date object using the timestamp
// multiplied by 1000 to convert seconds to milliseconds.
const date = new Date(unixTimestamp * 1000);
// Extract the hours from the timestamp
const hours = date.getHours();
// Extract the minutes from the timestamp
let minutes = "0" + date.getMinutes();
// Extract the seconds from the timestamp
let seconds = "0" + date.getSeconds();

// Format the time as HH:mm:ss
const formattedTime = `${hours}:${minutes.substr(-2)}:${seconds.substr(-2)}`;

console.log(formattedTime);

Answer №3

let timeInMilliseconds = 1575909015000

const dateInfo = new Date(timeInMilliseconds)

const formattedDate = dateInfo.toLocaleString() //2019-12-9 10:30:15

dateInfo.toLocaleString("en-US", {weekday: "long"}) // Monday
dateInfo.toLocaleString("en-US", {month: "long"}) // December
dateInfo.toLocaleString("en-US", {day: "numeric"}) // 9
dateInfo.toLocaleString("en-US", {year: "numeric"}) // 2019
dateInfo.toLocaleString("en-US", {hour: "numeric"}) // 10 AM
dateInfo.toLocaleString("en-US", {minute: "numeric"}) // 30
dateInfo.toLocaleString("en-US", {second: "numeric"}) // 15
dateInfo.toLocaleString("en-US", {timeZoneName: "short"}) // 12/9/2019, 10:30:15 AM CST

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 you explain the significance of triple brackets (e.g. {{{ content }}}) in the context of Javascript/Typescript?

As I delve into the code of a fresh project in which I hope to contribute, I have come across numerous methods defined with triple brackets, like so: deinitialize() {{{ this.destroyed = true; $(window).off("resize", this.resize as () => void); ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Retrieve JSON data within an HTML element, where the element is sourced from an AJAX GET response

What is the best way to extract JSON data from the response below? $.get('http://localhost:8000/json', function(response) { alert(response); }); The response is as follows: <div id="dom-target" style="display: none;"> {"logo":"log ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

Motion graphics following the completion of a form input

In my HTML, I've created a div container with a form field: <div class="flex_item" id="b_one"> <form id="f_one"> <input id="i_one" type="text"> </form> </div> I'm attempting to change the backgroun ...

What is preventing me from utilizing the import syntax to bring in a coffeescript file within typescript?

So here's the deal: I've got a typescript file where I'm importing various other typescript files like this: import ThingAMajig from '../../../libs/stuffs/ThingAMajig'; // a typescript file However, when it comes to importing my ...

Encountering TypeScript errors when utilizing it to type-check JavaScript code that includes React components

My JavaScript code uses TypeScript for type checking with docstring type annotations. Everything was working fine until I introduced React into the mix. When I write my components as classes, like this: export default class MyComponent extends React.Compo ...

Similar to tabpanel's ._hide() function, how can this be implemented in C#?

Even though I feel like I've tackled this issue in the past, I can't seem to locate a resolution anywhere... In my situation, there are 3 tabs within an ajax TabContainer and two CheckBoxes located outside of it. All 3 tabs are visible unless bo ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

Viewing a JSON object on the Firebase console

Is there a way to neatly log JSON data to the firebase logs? When I use: console.log(req.body) or console.log(`${req.body.event}: ${JSON.stringify(req.body, null, 2)}`); it displays the output on multiple lines as shown in the image below. I am runnin ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Tips for validating multiple inputs of the same type with identical names in JavaScript

I have limited experience with Javascript and am facing an issue with a HTML form that contains multiple input types with the same names occurring more than once. My goal is to validate the form before inserting the data into the database. I have managed t ...

Detecting Typescript linting issues in VSCode using Yarn version 3.2.3

Every time I try to set up a new react or next app using the latest yarn v3.2.3, my VS Code keeps showing linting errors as seen in the screenshot below. The main error it displays is ts(2307), which says Cannot find module 'next' or its correspo ...

Expand the boundaries of the MUI Select to encompass a different element

Is there a way to extend the border of the MUI Select dropdown menu around the IconButton next to it? I have set up sorting options (A-Z, newest-oldest) using the Select component and included a button to reverse the direction (Z-A, oldest-newest). However ...

Inquiring about Vue component prop defaults and detecting when a user has not assigned a value

1. I am looking for a way to set a default value for a component prop in Vue 2. Take, for example, a basic movies component that can be utilized like this: <movies year="2016"><movies> Vue.component('movies', { props: ['yea ...

Steps to assign the identifier as the current index in the v-for iteration

Struggling to assign the id based on the index of a v-for loop. I attempted: <li v-for="(item, index) in items" v-bind:key="item.id"> <p>{{item.name}}</p> <input id= {{index}} type= "number"> < ...

Distinguishing between client side rendering and server side rendering is the backbone of web development

My goal is to give users the option to request webpages from my website either directly from the server or by clicking on links, which will be managed by Backbone's router. When a user requests a webpage directly from the server, they will receive a ...

Gruntjs Live Reload is actively monitoring for changes, yet fails to refresh the page

Check out my Gruntfile.js here Also, take a look at my package.json here I ran npm install in the main directory of my workspace (using WAMP) and it created a node_modules folder along with several subfolders. After navigating to the directory c:\w ...

Obtain the native element of a React child component passed through props, along with its dimensions including height and width

Is there a way in React to access the native HTML element or retrieve the boundaries of an element passed as a child in props? Consider the following component: class SomeComp extends Component { componentDidMount() { this.props.children.forEa ...

What is the best way to incorporate progressive JPEG images onto a website?

I am currently working on a website called winni.in that is built using Java, Html, and Javascript. I would like to incorporate progressive image rendering upon page load, but I lack the necessary knowledge. I have come across and explored the following re ...