Generate a moment using the epoch time stamp

I am looking to utilize Moment.js for time management purposes.

My goal is to convert a string into a moment object and then convert it to milliseconds.

This is how I am currently attempting to achieve this:

const str = "1:12.123"; // 1m, 12s, 123ms = 72123ms
const parsed = moment(str, "m:ss.SSS");

The issue I am encountering is that the moment created by this method is based on "today" rather than epoch time.

console.log(parsed); // moment("2018-10-27T00:01:12.123")
console.log(parsed.unix()); // 1540609272, not 72123

Is there a way to parse a string based on epoch time instead of using today's date? Alternatively, do I need to manually convert the string to a number and calculate milliseconds myself?

Answer №1

In the realm of time, a moment is just a point in time, what you actually need is a measure of duration. According to Moment.js' documentation:

... while moments pinpoint specific instances, durations represent lengths of time. Durations lack a distinct start and end date.

To work with a duration in Moment.js, you can utilize one of its predefined objects like this:

const d = moment.duration('0:1:12.123');
console.log(d.asMilliseconds());

Make sure to include the leading 0: in the string, indicating the number of hours, as it helps moment.duration understand the input format correctly.

For further guidance, refer to the detailed documentation provided here: Moment.js | Docs

Additional Information:

Your mention of the epoch seems to reference January 1 of year 0, but in computing terms, the commonly referred to epoch is usually the Unix Epoch: 1970-01-01. Requesting milliseconds from the epoch could yield significantly more years than anticipated.

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

Validating a string as a date input by utilizing the moment library

Utilizing the momentjs library for validating dates can be tricky. The typical format for validation is as follows: moment(date, formats, true).isValid() However, if you only want to check if a string is a valid date without specifying a format, things ...

Adding a class to a child component layout from a parent component in Angular 12 and Typescript can be achieved by using the ViewChild decorator

Incorporating the child component into the parent component is an important step in the structure of my project. The dashboard component serves as the child element, while the preview component acts as the parent. Within the parent (preview) component.htm ...

Handling events in React using TypeScript

Currently diving into the world of React with Typescript and encountered a challenge involving event handling using the onClick property. I have a react component displaying a list of items from an array, and I aim to log the clicked item in the console. I ...

I encountered an error while running a basic express app with ts-node-dev: Invalid argument: A non-string value was provided to `ts.resolveTypeReferenceDirective`

Recently, I started diving into Typescript and Express. Trying to set up a basic Express app using ts-node-dev, I encountered the following error: > ./node_modules/.bin/ts-node-dev src/index.ts 16:07:40 [I ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Store the date in the database using the following format: dd/MM/yy

Can Grails save date values in the dd/MM/yy format in the database? While I can customize the display format in views, I also need the date values to be returned as JSON in that particular format. Any suggestions on how to achieve this would be greatly a ...

javascript assign array to object key

Looking at this basic array: const arr = [ { "id": 2, "color": "red" }, { "id": 1, "color": "blue" }, { "id": 2, "color": "yellow" ...

Converting JSON to Date and storing it as a List in the Controller of an MVC3 application

Within a View, the model is sent encoded like so: var model = '@Html.Raw(Json.Encode(Model))'; to a Controller Action. The model consists of a list of movies, each containing a release Date. Shown below is the Controller action method: [HttpPo ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...

Using ownProps as a parameter when passing it into a component that has been wrapped by

Update: Added some additional details Utilizing the Apollo graphql wrapper to wrap a component, I aim to pass the onPaymentLoaded property from OwnProps into the wrapped function. Despite my efforts, the code does not proceed beyond the TypeScript compile ...

Obtain the GMT date for the next day

Need help with code to get the current date and the current date + 1 day (in GMT). var now = new Date(); var newexp = (now + 3); var show = newexp.getGMTString(); alert(show); Goal is to set a cookie to expire in 1 day. function SetCookie(name, value, ...

Guide on troubleshooting *.ts files in an ionic 2 project using Chrome's inspect devices feature

After successfully creating my Ionic 2 application for Android using the command "ionic build android", everything seems to be working fine. I have been debugging the app by using Chrome inspect devices, but now I am facing an issue. I am trying to debug ...

Transforming the Date into Local Time: An Instantaneous Process?

I am currently working with a Kendo UI MVC grid that contains three date columns. These dates, which do not include any time values, are stored in the database as local time rather than UTC. The columns within the grid are defined like so: col ...

How can multiple setState calls be safely executed in a React event handler?

I'm facing a challenge with the following code: function App() { // array to store 3 numbers, all initialized to 0 const [counter, setCounter] = React.useState<number[]>([0, 0, 0]); // increments counter[i] by 1 co ...

Angular Kendo UI offers the ability to customize the way grid columns are sorted

I'm currently working on a Kendo Grid (UI for Jquery) where I have implemented a custom sort method for a specific column based on my customers' requirements. field: "daysLeft", title: "Accessible", width: 130, sortable: { compare: function (a ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

Error in Angular 2: Unable to connect to 'customer' as it is not recognized as a property of 'my-customer'

I have encountered an issue while following an outdated tutorial by John Papa and Buddy Ward. Despite reading various Stack Overflow posts, I still can't resolve the problem. The solution suggested avoiding the use of directives: in my component and i ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...