Date difference in hours - Angular 2 - date

How can I get difference in hours between two dates in angular2? I don't want to use external libs like moment.js.
Having, for example: incidentTime = '2017-03-05 11:26:16 AM' and creationTime = '2017-03-06 12:26:16 AM'
let time = +params.data.incidentTime - +params.data.creationTime;
console.log("time: " + time);
It should return 25 hours, but It returns NaN.

This should do the job:
const date1 = params.data.incidentTime;
const date2 = params.data.creationTime;
const diffInMs = Date.parse(date2) - Date.parse(date1);
const diffInHours = diffInMs / 1000 / 60 / 60;
console.log(diffInHours);
Use Math.floor to round the result down, or Math.ceil to round it up

parse the date type parameters to javascript's Date type.
let date1 = new Date(params.data.incidentTime).getTime();
let date2 = new Date(params.data.creationTime).getTime();
let time = date1 - date2; //msec
let hoursDiff = time / (3600 * 1000);

Try this:-
let time:any = new Date("2017-03-05 11:26:16").getHours();
let date2:any = new Date("2017-03-06 12:26:16").getHours();
console.log(time -date2, time, date2, "sdfsd");
but It returns NaN
this is because you are using + sign before date which is converting youtr date into number format so returning NAN(not a number)

Related

Date to Excel timestamp

I need to calculate an Excel "timestamp" (reference 01.01.1900, not 1970 like the unix timestamp) ; here what I did:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
excelTimestamp = unixTimestamp / 86400;
def startPoint= new GregorianCalendar(1900, Calendar.JANUARY, 0, 0,0,0).time;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = (unixTimestamp - startPoint.time/1000) / 86400;
the latter returns 1 day less, and 1 hour more... what did I wrong ?
the solution was MUCH easier:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = 25569 + (unixTimestamp+howmany)/86400;

Convert Minutes to HH:MM:SS - Swift

I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5
Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.
stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)
What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter to display the resulting seconds time interval using .positional units style to the user:
let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
defer { n /= 60 }
return $0 + $1 * n
}
let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds)) // "00:18:30"

Trying to calculate time difference, but am receiving negative answer

I am trying to calculate the time difference (x hrs x mins) between two timings, the current time, and the time set by user with the timepicker.
I would receive a negative value, e.g. -7 hrs 30 mins.
To solve this, I've read that i will need to include if statement. However, i receive the following error and am unable to solve it:
"Cannot convert value of type 'Date' to expected argument type 'TimeInterval' (aka 'Double')"
would greatly appreciate some help, thanks!
func findTimeDiff() {
let time1 = currentTimeOutlet
let time2 = alarmTimeOutlet
let formatter = DateFormatter()
formatter.dateFormat = "hh:mma"
let date1 = formatter.date(from: time1!.text!)
let date2 = formatter.date(from: time2!.text!)
var elapsedTime = date2!.timeIntervalSince(date1!)
let hours = floor(elapsedTime / 60 / 60)
let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
if (date2!) < (date1!) {
var elapsedTime = ((date2! + 86400000) - date1!)
let hours = floor(elapsedTime / 60 / 60)
let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
timeDiffOutlet.text = ("\(Int(hours)) hr and \(Int(minutes)) min")
}
else {
var elapsedTime = date2!.timeIntervalSince(date1!)
let hours = floor(elapsedTime / 60 / 60)
let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
timeDiffOutlet.text = ("\(Int(hours)) hr and \(Int(minutes)) min")
}
}
You should avoid performing calculations with hard coded values like this where dates and times are concerns. Instead it's much better to use the methods provided for you by the Calendar class.
So something like this:
func findTimeDiff2() {
let time1 = currentTimeOutlet
let time2 = alarmTimeOutlet
let formatter = DateFormatter()
formatter.dateFormat = "hh:mma"
let date1 = formatter.date(from: time1!.text!)
let date2 = formatter.date(from: time2!.text!)
let components = Calendar.current.dateComponents([.hour, .minute], from: date1!, to: date2!)
timeDiffOutlet.text = "\(abs(components.hour!)) hr and \(abs(components.minute!)) min"
}
Doing this means that situations such as daylight saving time will be handled for you although in this case as you don't know the day on which the alarm is taking place you won't be able to know if daylight saving applies or not. It would really be better to use a full date instead of just the time.
Why are you trying completely different expression in case of (date2!) < (date1!) ?
Try changing this line:
var elapsedTime = ((date2! + 86400000) - date1!)
To:
var elapsedTime = date1!.timeIntervalSince(date2!)

Swift: NSDate minus NSDate in hours

I have a model in Swift with an NSDate field named expirationDate and I want to calculate the hours remaining before expiration based on the current date.
Is there an easy way to do this with existing NSDate functionality?
Can't check now, but should be something like
expirationDate.timeIntervalSinceNow / 3600
Just find the number of seconds (NSTimeInterval) between the two dates ('now' and your expiration date) and divide by 60*60 = 3600:
let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate());
let hoursUntilExpiration = secondsUntilExpiration / 3600
For example:
7> let now = NSDate()
now: NSDate = 2016-02-01 03:44:06 UTC
8> let expirationDate = now.dateByAddingTimeInterval(60*60*10) // ten hours from now
expirationDate: NSDate = 2016-02-01 13:44:06 UTC
9> let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate());
secondsUntilExpiration: NSTimeInterval = 35991.422316968441
10> let hoursUntilExpiration = secondsUntilExpiration / 3600
hoursUntilExpiration: Double = 9.9976173102690122
// Slightly less than the 10 hours above because of the time it took me to type.

GWT converting current date to GMT

I am converting the current date to GMT time.
The result is in-consistent, due to this my date time calculations are going worng.
DateTimeFormat df = DateTimeFormat.getFormat("dd MMM yyyy hh:mm:ss");
String gmtStr = new Date().toGMTString().replace("GMT", "").trim();
long deptime= depTime - df.parse(gmtStr).getTime();
deptime = deptime / 1000;
seconds = (deptime % 60);
minutes = (deptime % 3600) / 60;
hours = (deptime / 3600);
Not sure what the best way is, but you could use the getTimezoneOffsert:
final Date gmtDate = new Date();
final Date offDate = new Date(gmtDate.getTime() + gmtDate.getTimezoneOffset() * 60 * 1000);
The offDate when displayed with DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_LONG) will still show the utc/gmt offset, because basically you have create a new time in the current timezone, but it matches the time of the GMT time and the long value returned from getTime() will be the number of milliseconds you can use in your calculation.