Suppose there are two dates A(start time) & B(end time). A & B could be the time on the same day or even different day. My task is to show difference in seconds. Date format which i am using is
Date Format :: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
For e.g.
start date :: "2011-11-16T14:09:23.000+00:00" end date :: "2011-11-17T05:09:23.000+00:00"
Help is appreciated.
To get the number of seconds between 2 dates: Get the number of milliseconds between the unix epoch and the Dates. Subtract the milliseconds of the start date from the milliseconds of the end date. Divide the result by the number of milliseconds in a second (1000).
getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.
Date Difference Extension in Swiftlet formatter = DateFormatter() formatter. dateFormat = "yyyy/MM/dd HH:mm" let xmas = formatter. date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear!
Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.
Use the Seconds
class:
DateTime now = DateTime.now(); DateTime dateTime = now.plusMinutes(10); Seconds seconds = Seconds.secondsBetween(now, dateTime); System.out.println(seconds.getSeconds());
This piece of code prints out 600. I think this is what you need.
As further advice, explore the documentation of joda-time
. It's pretty good, and most things are very easy to discover.
In case you need some help with the parsing of dates (It's in the docs, really), check out the related questions, like this:
Parsing date with Joda with time zone
The answer of @pcalcao will be best in most cases. Be aware that seconds will be rounded to an integer.
If you are interested in sub-seconds accuracy just substract the milliseconds:
double seconds = (now.getMillis() - dateTime.getMillis()) / 1000d;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With