I am trying to get the difference between 2 datetimestamps which look like These:
2018-08-22 00:00:00
2018-08-11 15:34:31
I want to Show the difference in time in days - Hours - minutes - seconds left.
So far I did this but it Always return NaN:
import moment from 'moment';
const calc = {
render () {
moment().format();
this.calcDifference();
},
calcDifference() {
let releaseDate = document.getElementById('release-at').value;
let currentDate = document.getElementById('current-date').value;
let ms = moment(
releaseDate,
"DD-MM-YYYY HH:mm:ss").diff(moment(currentDate,
"DD-MM-YYYY HH:mm:ss")
);
let d = moment.duration(ms);
let s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log(ms);
console.log(d);
console.log(s);
}
};
calc.render();
on your calcDifference function, you can do something like this
let releaseDate = moment('2018-09-22 00:00:00');
let currentDate = moment('2018-08-11 15:34:31');
const diff = releaseDate.diff(currentDate);
const diffDuration = moment.duration(diff);
console.log(`
${diffDuration.months()} months
${diffDuration.days()} days
${diffDuration.hours()} hours
${diffDuration.minutes()} minutes
${diffDuration.seconds()} seconds left!`);
in case values from release-at and current-date elements have format
DD-MM-YYYY HH:mm:ss, use
let releaseDate = moment(document.getElementById('release-at').value, 'DD-MM-YYYY HH:mm:ss');
let currentDate = moment(document.getElementById('current-date').value, 'DD-MM-YYYY HH:mm:ss');
Here's a working codepen
I hope it helps! :)
Related
I have a ScrapeResult mikroOrm entity, I am trying to create a new Date by using this piece of code newScrapeResult.date = new Date() and I am getting 2022-07-17T17:07:24.494Z this output.
I need to convert the above format to yyyy-mm-dd hh mm ss this format. How can I do this? I will save this format to database.
This might help you
function currentTime() {
let date = new Date()
let a = date.getFullYear()
let b = date.getMonth()+1 // JS months are 0 indexed, 0 = January, 11 = December
let c = date.getDate()
let d = date.getHours()
let e = date.getMinutes()
let f = date.getSeconds()
return a+'-'+b+'-'+c+' '+d+' '+e+' '+f
}
console.log(currentTime())
I am trying to get the time that has happened between two dates.
Example:
oldDate = "4/16/2020, 12:00:00"
today = "5/17/2021, 1:00:50"
Result that a need:
years = 1
months = 1
days = 1
hours = 1
minutes = 0
seconds = 50
I also would like to refresh it every second, so that, the user can see it running.
Thanks.
Use Date.parse() to get a Date object from a string, subtract two dates using the - operator, and get the number of years, months, days, etc. using the corresponding methods. Then use setInterval to run it every second, and Date.now() to get the current time.
const oldDate = Date.parse("4/10/2020, 12:00:00");
// weird but seems to work with all dates
const getYear = (date) => date.getFullYear() - 1970;
const timeBetweenDates = (date1, date2) => {
const date = new Date(date1 - date2);
return {
years: getYear(date),
months: date.getMonth(),
days: date.getDay(),
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds(),
}
}
const pre = document.getElementById("display");
setInterval(() => {
pre.textContent = JSON.stringify(
timeBetweenDates(Date.now(), oldDate),
0,
2
);
}, 1000);
<pre id="display">Wait a second...</pre>
I need to convert days hours min sec into a timestamp
eg:timerTime: "0-47-15-31";
into timestamp 1620148830209
can anyone help with this?
Assuming that you are working in UTC.
function getTimeStamp(dateString) {
splitted = dateString.split('-')
var date = new Date();
date.setDate(splitted[0])
splitted.shift();
date.setHours.apply(date,splitted);
return date.getTime();
}
getTimeStamp("0-47-15-31");
/// return 1619891131992
Timestamp from when?
Here are all the tools you need.
const timerTime = "0-47-15-31";
const [days,hours,minutes,seconds] = timerTime.split("-")
const d = new Date()
d.setDate(d.getDate() + +days); // cast the days to number
d.setHours(hours,minutes,seconds,0)
console.log(d,d.getTime(),1620148830209); // difference is timezone offset
// timestamp 1620148830209
I want to subtract lunch hours from datetime differece
How it can be achieved?
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 08:00:00.0
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 18:00:00.0
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss"); //00:30:00
var lunchTimeMs= moment(Lunch,"HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
ms = moment().subtract(lunchTimeMs); //This gives wrong result
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Total time " + i + " row" + s);
He is using Moment JS.
As far as I understood, the problem is that he has only date with time to manipulate in format similar to: dd.mm.YYYY HH:ii:ss.
My recommendation was to transfer server response datetime to timestamp using JS. It's much easier to manipulate date and time differences if you are using a timestamp.
UPDATE
Adding here my "vision" of JS date management (my fiddle). Feel free to improve it!
const date2timestamp= function(str){
_tmp = str.split(" ");
if(_tmp){
date_arr = ( _tmp[1] ? _tmp[0].split("-") : null );
time_arr = ( _tmp[1] ? _tmp[1].split(":") : _tmp[0].split(":") );
if(!date_arr) {
const today = new Date();
_date = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), time_arr[0], time_arr[1], time_arr[2]);
}
else {
_date = Date.UTC(date_arr[0], date_arr[1]-1, date_arr[2], time_arr[0], time_arr[1], time_arr[2]);
}
date_obj = new Date(_date);
return date_obj.getTime()/1000;
}
return false;
}
document.write(
date2timestamp("2020-04-20 08:00:00")+"<br/>",
date2timestamp("2020-04-20 17:00:00")+"<br/>",
date2timestamp("00:03:00")
);
And now you have timestamps. When you subtract, you know, that the 1min = 60sec, so the result is ((7*60)+30)*60 = date2timestamp("2020-04-20 17:00:00")-date2timestamp("2020-04-20 17:00:00")-(30*60)
MORE UPDATES
But, reading about the moment.js a bit, there is even easier way. Manual for subtract says:
moment().subtract(1, 'seconds');
that means, you have to actually transfer your Launch period into seconds and then add put it into the subtract: moment().subtract((30*60), 'seconds') or just add (for test) 'millisecond' as second part of subtract:
...
ms = moment().subtract(lunchTimeMs, 'milliseconds');
// or use that
ms = moment().subtract(lunchTimeMs/1000, 'seconds);
...
Try this:
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss");
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss");
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
moment(ms).subtract(Lunch);
So this is a new one to me. I've been working with this api and they returned a date in json format that looks like this
{
DateAdd: "/Date(1582936941390-0600)/"
}
not exactly sure how to convert this to a datetime like in the format below so I can actually do something with it.
2020-03-13 23:08:00
i have never seen this date format before! Thanks
Use moment.js to convert the date format
var data = {
DateAdd: "/Date(1582936941390-0600)/"
}
var datam = moment(data.DateAdd)
console.log(datam.format("YYYY-MM-DD HH:mm:ss")) // 2020-02-29 07:42:21
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
If you don't care about the timezone, you can just cut the timestamp out of that string:
const dateString = data.DateAdd;
const date = new Date(Number(dateString.match(/\d+/)[0]));
You can convert date into desired format by Javascript date object.
let addZero = (i) => {
if (i < 10) {
i = "0" + i;
}
return i;
}
let formatDate = (date) => {
let year = date.getFullYear(),
month = addZero(date.getMonth() + 1),
day = addZero(date.getDate() + 1),
hours = addZero(date.getHours() + 1),
minutes = addZero(date.getMinutes() + 1),
seconds = addZero(date.getSeconds() + 1);
let dateArr = [year, month, day];
let timeArr = [hours, minutes, seconds];
let result = dateArr.join('-').concat(" ", timeArr.join(':'));
return result;
}
let inputString = "/Date(1582936941390-0600)/";
let inputData = new Date(Number(inputString.match(/\d+/)[0]));
console.log(formatDate(inputData));
Please read more about Javascript date object