Convert hours and minute to millisecond using javascript or jQuery - javascript

I have Hours:Minute format of time as string. To display it into highchart as time i need to convert this string into milliseconds.
For example: 34:26 (34 hours and 26 minutes) millisecond is 124000000
How can i convert it to milliseconds using any of jquery or javascript function.

Try this code:
const toMilliseconds = (hrs,min,sec) => (hrs*60*60+min*60+sec)*1000;
console.log(toMilliseconds(34, 26, 0)); // --> 123960000ms

This is simple.
var time = "34:26";
var timeParts = time.split(":");
console.log((+timeParts[0] * (60000 * 60)) + (+timeParts[1] * 60000));

Arrow functions + hoisting variation with ES2015:
// Function
const milliseconds = (h, m, s) => ((h*60*60+m*60+s)*1000);
// Usage
const result = milliseconds(24, 36, 0);
// Contextual usage
const time = "34:26";
const timeParts = time.split(":");
const result = milliseconds(timeParts[0], timeParts[1], 0);
console.log(result);
This way you can componetize or make it service

Related

Get timezone from date string in JavaScript

I'm working on a function that should check if a given dateString has the same timeZone as the browser timeZone. To get the browser timeZone I can use either a) Intl.DateTimeFormat().resolvedOptions().timeZone which will return Europe/Amsterdam for example or b) new Date().getTimeZoneOffset() that will return -60. Both are fine.
The tricky part is to get the timeZone from the dateString I want to pass, for example from: 2021-01-01T00:00:00-05:00 (which should be America/New_York or 300 AFAIK). How can I get the timeZone from that date? I tried to do: new Date('2021-01-01T00:00:00-05:00').getTimeZoneOffset() but that will convert it to the timeZone of my browser again, returning -60.
Example of function:
function isSameTimeZone(date) {
// function to get time zone here
const a = getTimeZone(date)
return a === new Date().getTimeZoneOffset() || Intl.DateTimeFormat().resolvedOptions().timeZone
}
Testcases
2021-01-01T00:00:00-08:00 (SF)
2021-01-01T00:00:00-05:00 (NY)
2021-01-01T00:00:00+05:30 (Mumbai)
2021-01-01T00:00:00+01:00 (Amsterdam)
Anyone out there with a solution? Thanks in advance!
Here's my method;
function checkTimezone(dateString) {
const testDate = new Date(dateString);
const dateRegex = /\d{4}-\d{2}-\d{2}/;
const myDate = new Date(testDate.toISOString().match(dateRegex)[0]);
return !(testDate - myDate);
}
const testCases = ['2021-01-01T00:00:00-05:00', '2021-01-01T00:00:00-08:00', '2021-01-01T00:00:00-05:00', '2021-01-01T00:00:00+05:30', '2021-01-01T00:00:00+01:00'];
testCases.forEach(testCase => console.log(checkTimezone(testCase)));
So here's how it works, you pass in your date string and create a new Date() instance with it.
Then I get the ISO string with the Date.ISOString() method and match it with the original string to get the date and create another Date instance from it without the time.
Then I find the difference (comes in milliseconds), and convert it to minutes
So I've been testing around a bit and in the end I came up with the following solution, based on the dates I provided in my question.
const getTimeZoneOffsetFromDate = date => {
/*
Check if the offset is positive or negative
e.g. +01:00 (Amsterdam) or -05:00 (New York)
*/
if (date.includes('+')) {
// Get the timezone hours
const timezone = date.split('+')[1]
// Get the hours
const hours = timezone.split(':')[0]
// Get the minutes (e.g. Mumbai has +05:30)
const minutes = timezone.split(':')[1]
/*
Amsterdam:
const offset = 01 * -60 = -60 + -0 = -60
*/
const offset = hours * -60 + parseInt(-minutes)
return offset === new Date().getTimezoneOffset()
}
// Repeat
const timezone = date.slice(date.length - 5)
const hours = timezone.split(':')[0]
const minutes = timezone.split(':')[1]
/*
New York:
const offset = 05 * 60 = 300 + 0 = 300
*/
const offset = hours * 60 + parseInt(minutes)
return offset === new Date().getTimezoneOffset()
}
console.log(getTimeZoneOffsetFromDate('2021-01-01T00:00:00+01:00'))

Difference between two time using dayjs

I have two inputs of time and I want to get the difference/time-interval between these two using dayjs
fromtime = '13:00'
totime = '17:00'
So the output for the above two should be 4:00 hours
I tried
console.log(
dayjs(fromtime).diff(dayjs(totime), "hours")
);
But am not getting the expected output.
I found the solution to this.
const fromtime = '11:20'
const totime = '12:30'
const ft = dayjs(`2000-01-01 ${fromtime}`);
const tt = dayjs(`2000-01-01 ${totime}`);
const mins = tt.diff(ft, "minutes", true);
const totalHours = parseInt(mins / 60);
const totalMins = dayjs().minute(mins).$m
This will give the output as totalHours = 1 and totalMins = 10.
Hope this help someone.
Dayjs expects a Date in a certain format (dayjs parse string) not just a time. However you can set the hour (dayjs set hour) without setting a certain date (dayjs parse now):
var fromtime = dayjs().hour(13)
var totime = dayjs().hour(17)
console.log(totime.diff(fromtime, "hours"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>
EDIT
What if the input contains fromtime = '10.25' and totime = '11.30'. So my output should be '1.05'. But when I follow your method the output is 1. Is there a way to solve this
You can set The minutes also (dayjs set minute). Unfortunately i do not see any formatting options for time-differences in that library. So we will have to calculate that on our own:
function formatInterval(minutes) {
let interval = [
Math.floor(minutes / 60).toString(), //hours ("1" - "12")
(minutes % 60).toString() //minutes ("1" - "59")
];
return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}
let fromtime = dayjs().hour(10).minute(25);
let totime = dayjs().hour(11).minute(30);
let interval = totime.diff(fromtime, "minute");
console.log(formatInterval(interval));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>
EDIT2
This will fail if the day switches between the two first lines
OK was assuming the fromtime will always be a smaller number than the totime ... if thats not the case we can just substract negative amount of minutes from the total amount of minutes in a day like so:
function formatInterval(minutes) {
let interval = [Math.floor(minutes / 60).toString(), (minutes % 60).toString()];
return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}
function getInterval(from, to) {
let [hoursA, minutesA] = from.split(':');
let [hoursB, minutesB] = to.split(':');
let timeA = dayjs().hour(hoursA).minute(minutesA);
let timeB = dayjs().hour(hoursB).minute(minutesB);
let interval = timeB.diff(timeA, 'minutes');
if(interval < 0) {
return formatInterval(24 * 60 + timeB.diff(timeA, 'minutes'));
}
return formatInterval(interval);
}
console.log(getInterval('23:00', '1:45'));
console.log(getInterval('10:25', '11:30'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>
// Addition, Difference between two time zones
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(timezone);
const d1 = dayjs((dayjs().tz('Europe/Kiev').format('YYYY-MM-DDTHH:mm')));
const d2 = dayjs((dayjs().tz('Europe/London').format('YYYY-MM-DDTHH:mm')));
console.log(d1.diff(d2, 'hours', true)); // 2
fromtime = '13:00'
totime = '17:00'
These are currently strings and you need to convert it into integers.
console.log(parseInt(fromtime) - parseInt(totime)) //4

Convert milliseconds to hours and minutes using Momentjs

I am new to Momentjs. I am trying to use it to convert milliseconds to hours and minutes. Below, x is milliseconds
x = 433276000
var y = moment.duration(x, 'milliseconds').asHours;
Can anyone help?
I ended up doing this...
var x = 433276000
var tempTime = moment.duration(x);
var y = tempTime.hours() + tempTime.minutes();
Try this:
var x = 433276000
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
console.log("hours:" + hours + " mins:" + mins);
You can create a Moment.js date from milliseconds using moment.utc().
var milliseconds = 1000;
moment.utc(milliseconds).format('HH:mm');
Using the moment-duration-format plugin:
moment.duration(ms).format("h:mm")
There is an easier way to achieve what you want.
This
moment('2000-01-01 00:00:00').add(moment.duration(1000)).format('HH:mm:ss');
Will output this
00:00:01
Not the fanciest, I know, but it is 100% pure moment js.
edit: Doesn't work for periods longer than 24h
This seems unsupported per this SO. Following this github issue, there's a moment-to-countdown plugin that you may be able to use.
But it seems you may want Countdown.js for this in the first place.
countdown(0, 433276000, countdown.HOURS | countdown.MINUTES).toString();
Note this does not take into account leap seconds, or leap anything for that matter, as it fixes to the Unix epoch (so it's not a pure time interval).
There really is no need to use Moment for this operation.
It can be written in a single line:
var hours = Math.round((450616708 / 1000 / 60 / 60) * 100) / 100;
or as function:
function millisecondsToHours(ms){
return Math.round((ms / 1000 / 60 / 60) * 100) / 100;
}
In Moment.js duration you can just use Math.trunc for hours if you are expecting it to be over 24hrs. hh:mm:ss format.
var seconds = moment.duration(value).seconds();
var minutes = moment.duration(value).minutes();
var hours = Math.trunc(moment.duration(value).asHours());
see it here: https://codepen.io/brickgale/pen/mWqKJv?editors=1011
Here is a function that formats it for you into a string.
function ms_to_str(val) {
let tempTime = moment.duration(val),
timeObj = {
years: tempTime.years(),
months: tempTime.months(),
days: tempTime.days(),
hrs: tempTime.hours(),
mins: tempTime.minutes(),
secs: tempTime.seconds(),
ms: tempTime.milliseconds()
},
timeArr = [];
for (let k in timeObj) {
if (Number(timeObj[k]) > 0) {
timeArr.push(`${timeObj[k]} ${k}`)
}
}
return timeArr.join(', ');
}
Then simply call ms_to_str(2443253) which returns 40 mins, 43 secs, 253 ms.
If you do not need to show milliseconds, simply comment off the ms: tempTime.milliseconds().toString().padStart(3, '0') line.
Momentjs itself doesn't support duration, in order to do so, we need a plugin moment-duration-format
To use this plugin follow these steps (for React-js)
import moment from 'moment';
import momentDurationFormatSetup from "moment-duration-format";
var time = moment.duration(value,unit).format('hh:mm:ss',{trim:false})
Note: I have used {trim: false} as extra parameter so that it doesn't trim out extra 0's in the beginning. You can omit it if you want "11:30" instead of "00:11:30".
function durationAsString(ms, maxPrecission = 3) {
const duration = moment.duration(ms)
const items = []
items.push({ timeUnit: 'd', value: Math.floor(duration.asDays()) })
items.push({ timeUnit: 'h', value: duration.hours() })
items.push({ timeUnit: 'm', value: duration.minutes() })
items.push({ timeUnit: 's', value: duration.seconds() })
const formattedItems = items.reduce((accumulator, { value, timeUnit }) => {
if (accumulator.length >= maxPrecission || (accumulator.length === 0 && value === 0)) {
return accumulator
}
accumulator.push(`${value}${timeUnit}`)
return accumulator
}, [])
return formattedItems.length !== 0 ? formattedItems.join(' ') : '-'
}
Lets you set max-precision and will not show insignificant values.
Examples:
durationAsString(0) will return -
durationAsString(10000) will return 10s
durationAsString(100000) will return 1m 40s
durationAsString(10000000) will return 2h 46m 40s
durationAsString(100000000) will return 1d 3h 46m
durationAsString(100000000, 4) will return 1d 3h 46m 40s
moment('2000-01-01 00:00:00').millisecond(XXXXXX).format("HH:mm:ss")

How to use format() on a moment.js duration?

Is there any way I can use the moment.js format method on duration objects? I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.
I'd like to be able to do something like:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.
Thanks!
// set up
let start = moment("2018-05-16 12:00:00"); // some random moment in time (in ms)
let end = moment("2018-05-16 12:22:00"); // some random moment after start (in ms)
let diff = end.diff(start);
// execution
let f = moment.utc(diff.asMilliseconds()).format("HH:mm:ss.SSS");
alert(f);
Have a look at the JSFiddle
convert duration to ms and then to moment:
moment.utc(duration.as('milliseconds')).format('HH:mm:ss')
We are looking into adding some kind of formatting to durations in moment.js. See https://github.com/timrwood/moment/issues/463
A couple other libraries that might help out are http://countdownjs.org/ and https://github.com/icambron/twix.js
Use this plugin Moment Duration Format.
Example:
moment.duration(123, "minutes").format("h:mm");
Use this line of code:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
var diff = moment(end).unix() - moment(start).unix();
moment.utc(moment.duration(diff).asMilliseconds()).format("HH:mm:ss.SSS");
The best scenario for my particular use case was:
var duration = moment.duration("09:30"),
formatted = moment.utc(duration.asMilliseconds()).format("HH:mm");
This improves upon #Wilson's answer since it does not access private internal property _data.
You don't need .format. Use durations like this:
const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23
I found this solution here: https://github.com/moment/moment/issues/463
EDIT:
And with padding for seconds, minutes and hours:
const withPadding = (duration) => {
if (duration.asDays() > 0) {
return 'at least one day';
} else {
return [
('0' + duration.hours()).slice(-2),
('0' + duration.minutes()).slice(-2),
('0' + duration.seconds()).slice(-2),
].join(':')
}
}
withPadding(moment.duration(83, 'seconds'))
// 00:01:23
withPadding(moment.duration(6048000, 'seconds'))
// at least one day
I needed to do this for work as a requirement to display the hours in this format.
At first I tried this.
moment.utc(totalMilliseconds).format("HH:mm:ss")
However anything over 24 hours and the hours reset to 0.
But the minutes and seconds were accurate.
So I used only that part for the minutes and seconds.
var minutesSeconds = moment.utc(totalMilliseconds).format("mm:ss")
Now all I need is the total hours.
var hours = moment.duration(totalMilliseconds).asHours().toFixed()
And to get that format that we all want we just glue it together.
var formatted = hours + ":" + minutesSeconds
if totalMilliseconds is 894600000 this will return 249:30:00.
Hope that helped. Leave any questions in the comments. ;)
I use:
var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");
And I get "09:30" in var str.
if diff is a moment
var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);
If you're willing to use a different javascript library, numeral.js can format seconds as follows (example is for 1000 seconds):
var string = numeral(1000).format('00:00');
// '00:16:40'
If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:
Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')
Based on ni-ko-o-kin's answer:
meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
withPadding = (duration) => {
var step = null;
return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
var nonEmpty = Boolean(n);
if (nonEmpty || step || i >= a.length - 2) {
step = true;
}
return step;
}).map((n) => ('0' + n).slice(-2)).join(':')
}
duration1 = moment.duration(1, 'seconds');
duration2 = moment.duration(7200, 'seconds');
duration3 = moment.duration(604800, 'seconds');
withPadding(duration1); // 00:01
withPadding(duration2); // 02:00:00
withPadding(duration3); // 01:07:00:00:00
I use the classic format function in these cases:
var diff = moment(end).unix() - moment(start).unix();
//use unix function instead of difference
moment.unix(diff).format('hh:mm:ss')
This is a hack because the time diff is treated as a standard moment date, an early epoch date time, but it doesn't matter to our goal and you don't need any plugin
Short version (one-liner):
moment.duration(durationInMs).asHours()|0||"00" + ":" + moment.utc(durationInMs).format("mm:ss")
Extended version:
export const formatDuration = (durationInMs) => {
const hours = Math.floor(moment.duration(durationInMs).asHours()) || "00"
return hours + ":" + moment.utc(durationInMs).format("mm:ss")
}
Example cases:
To format moment duration to string
var duration = moment.duration(86400000); //value in milliseconds
var hours = duration.hours();
var minutes = duration.minutes();
var seconds = duration.seconds();
var milliseconds = duration.milliseconds();
var date = moment().hours(hours).minutes(minutes).seconds(seconds).millisecond(milliseconds);
if (is12hr){
return date.format("hh:mm:ss a");
}else{
return date.format("HH:mm:ss");
}
if you use angular add this to your filters:
.filter('durationFormat', function () {
return function (value) {
var days = Math.floor(value/86400000);
value = value%86400000;
var hours = Math.floor(value/3600000);
value = value%3600000;
var minutes = Math.floor(value/60000);
value = value%60000;
var seconds = Math.floor(value/1000);
return (days? days + ' days ': '') + (hours? hours + ' hours ': '') + (minutes? minutes + ' minutes ': '') + (seconds? seconds + ' seconds ': '')
}
})
usage example
<div> {{diff | durationFormat}} </div>
My solution that does not involve any other library and it works with diff > 24h
var momentInSeconds = moment.duration(n,'seconds')
console.log(("0" + Math.floor(momentInSeconds.asHours())).slice(-2) + ':' + ("0" + momentInSeconds.minutes()).slice(-2) + ':' + ("0" + momentInSeconds.seconds()).slice(-2))
How to correctly use moment.js durations?
|
Use moment.duration() in code
First you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')
How about native javascript?
var formatTime = function(integer) {
if(integer < 10) {
return "0" + integer;
} else {
return integer;
}
}
function getDuration(ms) {
var s1 = Math.floor(ms/1000);
var s2 = s1%60;
var m1 = Math.floor(s1/60);
var m2 = m1%60;
var h1 = Math.floor(m1/60);
var string = formatTime(h1) +":" + formatTime(m2) + ":" + formatTime(s2);
return string;
}
Use moment-duration-format.
Client Framework (ex: React)
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
Server (node.js)
const moment = require("moment-timezone");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
moment.duration(x).format() has been deprecated.
You can usemoment.utc(4366589).format("HH:mm:ss") to get the desired response.
console.log(moment.utc(4366589).format("HH:mm:ss"))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
const duration = moment.duration(62, 'hours');
const n = 24 * 60 * 60 * 1000;
const days = Math.floor(duration / n);
const str = moment.utc(duration % n).format('H [h] mm [min] ss [s]');
console.log(`${days > 0 ? `${days} ${days == 1 ? 'day' : 'days'} ` : ''}${str}`);
Prints:
2 days 14 h 00 min 00 s
There is no longer (if there ever was) any need to convert duration to utc to solve this issue. This is like converting a base10 "1" to binary and then saying that since output "1" looks like base10 we'll have no issues assuming this is a base10 value for any further operations.
Use moment-duration-format and note that with { trim: false } you can prevent trimming:
moment.duration(1000000, "seconds").format("hh:mm:ss", { trim: false })
> "277:46:40"
moment.duration(0, "seconds").format("hh:mm:ss", { trim: false })
> "00:00:00"
Let's compare this with the not recommended method of using abusing utc:
moment.utc(moment.duration(1000000, "seconds").asMilliseconds()).format('HH:mm:ss')
> "13:46:40"
Just moment.js without any other plugins
moment().startOf('day').seconds(duration).format('HH:mm:ss')
import * as moment from 'moment'
var sleep = require('sleep-promise');
(async function () {
var t1 = new Date().getTime();
await sleep(1000);
var t2 = new Date().getTime();
var dur = moment.duration(t2-t1);
console.log(`${dur.hours()}h:${dur.minutes()}m:${dur.seconds()}s`);
})();
0h:0m:1s
You can use numeral.js to format your duration:
numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**
* PT1H30M -> 0130
* #param {ISO String} isoString
* #return {string} absolute 4 digit number HH:mm
*/
const parseIsoToAbsolute = (isoString) => {
const durations = moment.duration(isoString).as('seconds');
const momentInSeconds = moment.duration(durations, 'seconds');
let hours = momentInSeconds.asHours().toString().length < 2
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);
const minutes = momentInSeconds.minutes().toString().length < 2
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();
const absolute = hours + minutes;
return absolute;
};
console.log(parseIsoToAbsolute('PT1H30M'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
If you use Angular >2, I made a Pipe inspired by #hai-alaluf answer.
import {Pipe, PipeTransform} from "#angular/core";
#Pipe({
name: "duration",
})
export class DurationPipe implements PipeTransform {
public transform(value: any, args?: any): any {
// secs to ms
value = value * 1000;
const days = Math.floor(value / 86400000);
value = value % 86400000;
const hours = Math.floor(value / 3600000);
value = value % 3600000;
const minutes = Math.floor(value / 60000);
value = value % 60000;
const seconds = Math.floor(value / 1000);
return (days ? days + " days " : "") +
(hours ? hours + " hours " : "") +
(minutes ? minutes + " minutes " : "") +
(seconds ? seconds + " seconds " : "") +
(!days && !hours && !minutes && !seconds ? 0 : "");
}
}

JavaScript creating a Date Object x seconds Ago?

Say I have a number x that can be anything (within reason). How would I create a new Date object that is x number of seconds ago? I have no idea about how to approach this.
var seconds = 5;
var dateNow = new Date();
var date5SecondsAgo = new Date(dateNow.getTime() - seconds*1000);
var now = new Date();
var seconds = 15;
var before = new Date(now.getTime() - seconds*1000);
You can use the valueOf/getTime property to get the the number of milliseconds since Jan 1, 1970 and then there are 1,000 milliseconds in a seconds
var milliSecondPerSecond = 1000;
var myStartDate = new Date(myEndDateTime - numberOfSeconds * milliSecondPerSecond );
Here's a function to do this, which I'm using in a real project. I used Date.now() and provided a second parameter to make it easy to test.
export const backDate = (secondsAgo: number, now: number = Date.now()): Date =>
new Date(now - secondsAgo * 1000)
Here's a version without the typescript noise.
export const backDate = (secondsAgo, now = Date.now()) =>
new Date(now - secondsAgo * 1000)
You can call it without the now parameter to get what you want.
const thirtySecondsAgo = backDate(30)

Categories

Resources