I have two dates in millis 1513885098821 & 1513885078742.
How to display the difference between above two dates in hrs and mins like 2 hrs 31 mins.
If moment have any option then its good, solution using plain javascript is also ok for me.
I tried below
moment(new Date(txn.toDate - txn.fromDate)).format('HH mm')
But it gives 05 30 result. Output of below line is
new Date(1513885098821 - 1513885078742);
result: Thu Jan 01 1970 05:30:20 GMT+0530 (India Standard Time)
There are probably countless answers already to help you find the difference between two dates, either using moment js or simply the native javascript Date object. Since you are having difficulty though, here is an example using moment js and its diff function:
// use timestamps to create moment objects
const startDate = moment.utc(1513885098821);
const endDate = moment.utc(1513885078742);
const hourDiff = startDate.diff(endDate, 'hours');
console.log(hourDiff); // 0
const minuteDiff = startDate.diff(endDate, 'minutes');
console.log(minuteDiff); // 0
const secondDiff = startDate.diff(endDate, 'seconds');
console.log(secondDiff); // 20
console.log(`${hourDiff}hrs ${minuteDiff}mins ${secondDiff}sec`); // 0hrs 0mins 20sec
Or try it online here.
You don't need to use Date, just do this:
prettyMillisDiff(millis1, millis2) {
let minDiff = (millis1 - millis2)/60000;
if (minDiff < 0) {
minDiff *= -1;
}
const hours = Math.floor(minDiff/60);
const mins = Math.floor(minDiff%60);
console.log(`${hours} hours ${mins} mins`);
}
try splitting string from the first method.
var k=moment(new Date(txn.toDate - txn.fromDate)).format('HH mm');
var frmt=k.split(' ');
var min=frmt+'mm';
var hr=frmt+'fr';
Related
I need to add 4 hours to my moment js date. So for that i am using
/* this timestamp is this date 27-03-2045 00:00 */
const someday = moment(2374178400000);
const addedFourHours = someday.add(4, 'hours');
on 27 March the DST is already passed and i get exactly 4 hours added and the end date in addedFoursHours is Mon Mar 27 2045 04:00:00 GMT+0200.
But when i try date when DST is happening for example 26 March on midnight
/* this timestamp is this date 26-03-2045 00:00 */
const someday = moment(2374095600000);
const addedFourHours = someday.add(4, 'hours');
then i get Sun Mar 26 2045 05:00:00 GMT+0200. In previous case i got 04:00 time when i added 4 hours after midnight. Why in DST time i get 05:00 time ?
How can i solve this ?
You want to add 3, 4 or 5 hours depending on the date, but you want to set specific values for the hours. Read the hour value, add 4 and set the value:
const today = moment(2374178400000);
const four = moment(today).hours(today.hour() + 4);
const eight = moment(four).hours(four.hour() + 4);
const twelve = moment(eight).hours(eight.hour() + 4);
const sixteen = moment(twelve).hours(twelve.hour() + 4);
const twenty = moment(sixteen).hours(sixteen.hour() + 4);
const tomorrow = moment(twenty).hours(twenty.hour() + 4);
console.log(today);
console.log(four);
console.log(eight);
console.log(twelve);
console.log(sixteen);
console.log(twenty);
console.log(tomorrow);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
What you want is then actually not adding 4 hours, but finding the next time where the hours are a multiple of 4.
So, remove all suggestion from your code that you are adding four hours (cf. your variable name).
You can do this:
const someday = moment(2374095600000);
console.log(someday.toString());
const hours = someday.hours();
someday.hours(hours + 4 - (hours % 4)); // Find next time that is multiple of 4.
console.log(someday.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
I am using angular material datepicker
https://material.angular.io/components/select/overview
but this returns only the date and not the current time :
Mon May 28 2018 00:00:00 GMT+0530 (IST)
Is there any way I can get the current time also from this?
You can use the ngModelChange to parse the date before setting it to your model, I recommend you momentJS for easy date manipulations.
in the HTML
<input [ngModel]="date" (ngModelChange)="onDataChange($event)" matInput [matDatepicker]="picker" placeholder="Choose a date">
In your Component.ts
onDataChange(newdate) {
const _ = moment();
const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
this.date = date.toDate();
console.log({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
}
you can find the full solution here https://stackblitz.com/edit/angular-ecq2lc
Right now the material date picker provides just the current date (without the current time), but there is an open issue in the official repo, so we might see a time picker in the near future.
The angular material is not providing Time right now you need to manually get time from timeStamp, Try this -
function getTimeFromDate(timestamp) {
let date = new Date(timestamp * 1000);
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
return hours+":"+minutes+":"+seconds
}
let timeStamp = new Date("Mon May 28 2018 00:00:00 GMT+0530 (IST)")
console.log(getTimeFromDate(timeStamp));
For Example currenttime = Mon May 28 2018 00:00:00 GMT+0530 (IST)
Currenttime is an example if u using current date means just use new Date()
//Sample function calling Method
Exacttime(){
this.functionName = this.diffhours(new(currenttime))
}
diffhours(currenttime){
var diff = new Date(currenttime);
diff .getHours(); // => 9
diff .getMinutes(); // => 30
diff .getSeconds(); // => 51
}
I am working on a project that requires this kind of text response on a date object.
"1 day 7 hours away"
--- it needs to be this way - not "31 hours away" or "1 day away"
-- also I am using moment js - as I am doing language switching between English and German - so I've tapped into the moment.js language locale
moment.locale('de')
I am using moment js - currently I've created a fake date object
var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 7 hours
when I try and render the moment js
moment(futureDate).endOf('day').fromNow()
it just says "in a day"
How do I modify the moment function to handle 1 day 7 hours -- and maybe re-jig the sentence?
--- code snippet attempt
moment.locale('de') // switch between en and de -- english and german
var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 4 hours
// Results in hours
console.log(moment(futureDate).endOf('day').fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
code test 2 using difference
moment.locale('de') // switch between en and de -- english and german
var a = moment();
var b = moment(a).add(31, 'hours');
// Results in days
console.log(b.diff(a, 'days'));
console.log(b.diff(a, 'days', true));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
You can use relativeTimeThreshold and relativeTime (key of moment.updateLocale) to customize how moment shows relative time (e.g. the fromNow() output).
In your case, you can:
Adjust threshold to get difference in seconds (see: How to make moment.js show relative time in seconds?).
Create a duration object using moment.duration(Number, String).
Use moment-duration-format plug-in to show duration value in the format you prefer.
Here a live sample:
var momEn = moment().add({d:1, h:7});
var momDe = moment().locale('de').add({d:1, h:7});
console.log(momEn.fromNow()); // in a day
console.log(momDe.fromNow()); // in einem Tag
// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);
// Update relative time
moment.updateLocale('en', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return moment.duration(number, 's').format('d [day] h [hour]');
},
}
});
moment.updateLocale('de', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return moment.duration(number, 's').format('d [Tag] h [Uhr]');
},
}
});
console.log(momEn.fromNow()); // in 1 day 7 hour
console.log(momDe.fromNow()); // in 1 Tag 7 Uhr
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Unfortunately you have to manually update each locale you need to support.
You can do it with moment-duration-format or with moment.diff like so:
let futureDate = new Date ()
futureDate.setDate (futureDate.getDate () + 1)// add a day
futureDate.setHours (7)
let start = moment ()
let end = moment (futureDate)
// 1st solution: with moment-duration-format
console.log (moment.duration (end.diff (start)).format ('d [days] hh [hours]', { trim: false }))
// 2nd solution: diff without moment-duration-format
let hoursDuration = end.diff (start, 'hours')
console.log (Math.floor (hoursDuration / 24) + ' days ' + (hoursDuration % 24) + ' hours')
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
The first solution requires the additional moment-duration-format module, whereas the second does everything using moment.js only. Also, don't forget to npm install moment-duration-format before requiring it.
Edit: Since you mentioned you'd like to stick with Moment.js, they have moment#diff available:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Found from: https://stackoverflow.com/a/42187373/2803743
I'd use countdown.js for this.
var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 7 hours
var timePassed = countdown(Date.now().toString(), futureDate, countdown.DAYS|countdown.HOURS);
console.log(timePassed);
timePassed is a lovely object; in this example:
days: 0
end: Tue Jul 04 2017 07:17:41 GMT+0300 (EEST)
hours: 12
start: Mon Jul 03 2017 19:17:41 GMT+0300 (EEST)
units: 18
value: 43200000
Which you can then concat to your desired string.
It's not really documented well, but the lib also has a CDN
https://cdnjs.com/libraries/countdown
I'm comparing two dates; one returned as a UTC String (as part of an Ajax response) and the second in local browser time:
Basically, I want to see if the date returned (endTime) happened before right now. My code is below and I thought I had it right but it's not working.
var isActive = true;
var buffer = 30000; // 30 seconds
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
var nowUtc = new Date(now).toUTCString(); // "Fri, 23 Oct 2015 00:01:31 GMT"
var nowTimeMs = new Date(nowUtc).getTime(); // 1445558491000
var endTimeMs = endTime.getTime() + buffer; // 1445616104000
if( nowTimeMs > endTimeMs ){
isActive = false;
}
isActive should remain as true but instead it's false. I feel like I've been looking at this too long and am missing something very simple. Am I?
Thanks for any helpful tips.
Update:
Based on the responses I thought I'd update my question. What is the best way to compare two dates where one is this:
new Date(); // Thu Oct 22 2015 21:51:53 GMT-0400 (EDT)
...and the other is a String representation of date:
"2015-10-23 01:49:27"
I figure the best way to create a valid Date object out of the String is using this code.
isThisActive:function(p){
var isActive = true;
var buffer = 30000;
var pEndTime = myObj.parseStringAsDate(p.callEndTime);
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
now.setTime( now.getTime() + offset );
var nowTimeMs = now.getTime();
var endTimeMs = pEndTime.getTime() + buffer;
if( nowTimeMs > endTimeMs ){
isActive = false;
}
return isActive;
},
parseStringAsDate:function(str){
var dateTimeStr = str.split(" ");
var dateStr = dateTimeStr[0].split("-");
var year = dateStr[0];
var month = dateStr[1];
var day = dateStr[2];
var timeStr = dateTimeStr[1].split(":");
var hours = timeStr[0];
var minutes = timeStr[1];
var seconds = timeStr[2];
return new Date( year,month,day,hours,minutes,seconds);
}
Because "pEndTime" is in UTC I applied the offset to the "now" Date object but even this is not working. Where's the problem here? I thought this would solve it.
SOLVED:
The latest code I posted did work. I was just getting incorrect values for the response.endTime (It wasn't converted to correct military time). Thank you everyone for your input. I've tried to upgrade as many helpful responses as I could.
You should not use the Date constructor or Date.parse (which do the same thing) to parse date strings. Either write your own parse function (below) or use a well maintained library.
To parse the format in the OP, you can use:
// Parse Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
function parseMMMDY(s) {
var b = s.split(/\W/);
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var sign = /GMT-\d{4}/i.test(s)? 1 : -1;
var min = +b[5] + (sign * b[8].slice(0,2) * 60 ) + (sign * b[8].slice(-2));
return new Date(Date.UTC(b[3], months[b[1].toLowerCase().slice(0,3)], b[2], b[4], min, b[6]));
}
document.write(parseMMMDY('Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)'));
I think the problem is here:
var endTime = new Date(Date.parse(response.endTime));
respnonse.endTime is UTC, right? But when you parse it to Date value, Date.parse assumes it is in local timezone (GMT-0400 as in your example code). It means that the endDate gets the wrong value
I usually use moment.js in my projects which related to formatting date time, especially in the reports (I'm working in the field of finance). You must have one more library in your project but it provides many other functionalities
Sorry, this is for your new update. I haven't got enough 'population' to leave a comment :P
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
Your endTime doesn't seem to return a UTC date as you mentioned. It looks to be using (EDT) so maybe you didn't have to convert it to UTC.
I want to do same thing as
How do I get the number of days between two dates in JavaScript?
but I want do the same on this date format: 2000-12-31.
function daysBetween(date1String, date2String){
var d1 = new Date(date1String);
var d2 = new Date(date2String);
return (d2-d1)/(1000*3600*24);
}
console.log( daysBetween('2000-12-31', '2005-05-04') ); //-> 1585
ISO8601 date strings are recognized by JavaScript directly. No need to parse them yourself.
Try this.
var toDate = "2000-12-31";
var fromDate = "2000-10-30";
var diff = Math.floor(( Date.parse(toDate) - Date.parse(fromDate) ) / 86400000);
You wont be asking this question if you have checked the answer with more up-votes and not the marked answer on the link you have provided. :)
Well, it's not jQuery, but just as easy to work with. Check out DateJS. Can parse dates, differences, and more.
The other solutions here do not take into account the TimeZone information (which is fine if that is what you want)
but I came across a problem like this: I have two dates:
Thu Mar 01 2012 00:00:00 GMT+0100 and Sat Mar 31 2012 00:00:00 GMT+0200
which will give you 29.95833 days before the Math.floor and hence 29 days after the floor.
This is not the 30 days I was expecting. Clearly Daylight Saving has kicked in and shortened
one of the days by an hour.
Here is my solution which takes TimeZones into account:
function daysBetween(date1String, date2String) {
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_MINUTE = 1000 * 60;
var d1 = new Date(date1String);
var d2 = new Date(date2String);
var d1_ms = d1.getTime() - d1.getTimezoneOffset() * ONE_MINUTE;
var d2_ms = d2.getTime() - d2.getTimezoneOffset() * ONE_MINUTE;
return Math.floor(d1_ms - d2_ms/ONE_DAY);
}