I want to make a Calendar according to Timezone. I tried to resolve the issue by surfing different queries but i can't. Now it pick mobile default time. If anyone have idea please help me. Timezone should be UK time.
I tried:
{
Calendar c1;
c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
int hour = c1.get(Calendar.HOUR);
int minutes = c1.get(Calendar.MINUTE);
int seconds = c1.get(Calendar.SECOND);
int day = c1.get(Calendar.DAY_OF_MONTH);
int month = c1.get(Calendar.MONTH);
int year = c1.get(Calendar.YEAR);
}
But it also returns System date.
java.time
ZonedDateTime nowInUk = ZonedDateTime.now(ZoneId.of("Europe/London"));
int hour = nowInUk.getHour();
int minutes = nowInUk.getMinute();
int seconds = nowInUk.getSecond();
int day = nowInUk.getDayOfMonth();
Month month = nowInUk.getMonth();
int year = nowInUk.getYear();
System.out.println("hour = " + hour + ", minutes = " + minutes + ", seconds = " + seconds
+ ", day = " + day + ", month = " + month + ", year = " + year);
When I ran this snippet just now, it printed:
hour = 3, minutes = 41, seconds = 15, day = 5, month = OCTOBER, year =
2018
ZonedDateTime largely replaces the outdated Calendar class.
What went wrong in your code?
Time zone ID for UK time is Europe/London. In your code you used UTC, which is something else and wll give you a different result, at least sometimes. UK time coincides with UTC some of the year in some years, but not at this time of year this year. So you got a time that was one hour earlier than UK time.
Also c1.get(Calendar.HOUR) gives you the hour within AM or PM from 1 through 12, which I don’t think was what you intended.
Question: Can I use java.time on Android?
Yes, java.time works nicely on Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.
Use this method for get time from timezone but here is one condition must need to checked auto time in setting's otherwise move to setting's page.
private void setDateTime() {
// Settings.Global.putInt(getContentResolver(), Settings.Global.AUTO_TIME, 1);
try {
int value = Settings.Global.getInt(getContentResolver(), Settings.Global.AUTO_TIME);
if (value == 1) {
Log.i("value", String.valueOf(value));
{
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, new Locale("en", "in"));
String date = simpleDateFormat.format(new Date());
Log.i("get C_d_t", date);
txt_time.setText(date);
}
} else {
//move to settings
Toast.makeText(getBaseContext(), "Must need to checked automatic date & time", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS), 0);
}
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
}
Related
I have to take an action if the time falls between start and stop time and on a specific day. I referred some existing threads on SO to check if the time falls within the specified time range.
Say if start time is 23:00pm, stop time is 7:00am and current time is 2:00am. Just the time validity function returns true. But if I include days in this code, the function returns false. Eg: user selects [Monday, Tuesday, Wednesday]. Even though Thursday is not in the list, but the end time 7:00am falls on Thursday, action can be taken anytime between 23:00pm Wed - 7:00am Thu, but action cannot be taken on 23:00pm Thu or any days not mentioned in the list.
Below is my code:
private fun isCurrentTimeBetweenProvidedTime(context: Context): Boolean {
var reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$".toRegex()
val startTime = getStartTime()
val endTime = getEndTime()
val currentTime = getCurrentTime()
if (reg.containsMatchIn(startTime) && reg.containsMatchIn(endTime) && reg.containsMatchIn(currentTime)) {
var valid = false
var startTime = SimpleDateFormat("HH:mm:ss").parse(startTime)
var startCalendar = Calendar.getInstance()
startCalendar.time = startTime
var currentTime = SimpleDateFormat("HH:mm:ss").parse(currentTime)
var currentCalendar = Calendar.getInstance()
currentCalendar.time = currentTime
var endTime = SimpleDateFormat("HH:mm:ss").parse(endTime)
var endCalendar = Calendar.getInstance()
endCalendar.time = endTime
if (currentTime.compareTo(endTime) < 0) {
currentCalendar.add(Calendar.DATE, 1)
currentTime = currentCalendar.time
}
if (startTime.compareTo(endTime) < 0) {
startCalendar.add(Calendar.DATE, 1)
startTime = startCalendar.time
}
if (currentTime.before(startTime)) {
valid = false
} else {
if (currentTime.after(endTime)) {
endCalendar.add(Calendar.DATE, 1)
endTime = endCalendar.time
}
if (currentTime.before(endTime)) {
valid = true
} else {
valid = false
}
}
// This won't work if day is Thursday and time is 2:00am, even though time falls between 23:00-7:00
var todayCalendar = Calendar.getInstance()
if ((currentTime >= startTime && todayCalendar.get(Calendar.DAY_OF_WEEK) in selectedDays.values) &&
(currentTime <= endTime && (todayCalendar.get(Calendar.DAY_OF_WEEK) in selectedDays.values || todayCalendar.get(Calendar.DAY_OF_WEEK)-1 in selectedDays.values))) {
Log.d(TAG, "Days are valid")
}
return valid
}
return false
}
How do I handle the days scenario?
java.time and ThreeTenABP
Please note: This code can work on Android API levels both under and over level 26. I will explain further down. I will have to trust you to translate from Java code.
If I have understood your requirements correctly:
ZoneId zone = ZoneId.of("America/Chihuahua");
LocalTime startTime = LocalTime.of(23, 0);
LocalTime endTime = LocalTime.of(7, 0);
Set<DayOfWeek> selectedDays
= EnumSet.of(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY);
ZonedDateTime now = ZonedDateTime.now(zone);
LocalTime timeNow = now.toLocalTime();
DayOfWeek currentDayOfWeek = now.getDayOfWeek();
boolean inIntervalOnDay;
if (startTime.isAfter(endTime)) { // crosses midnight
if (timeNow.isBefore(endTime)) { // in interval, after midnight
// Day is correct if the day before is among the selected days
inIntervalOnDay = selectedDays.contains(currentDayOfWeek.minus(1));
} else if (timeNow.isBefore(startTime)) {
inIntervalOnDay = false;
} else { // after start time, before midnight
inIntervalOnDay = selectedDays.contains(currentDayOfWeek);
}
} else {
inIntervalOnDay = ! timeNow.isBefore(startTime)
&& timeNow.isBefore(endTime)
&& selectedDays.contains(currentDayOfWeek);
}
System.out.println("Now: " + now + " (" + currentDayOfWeek + ") Valid? " + inIntervalOnDay);
When I ran the snippet just now, the output was:
Now: 2019-09-27T03:47:56.856-06:00[America/Chihuahua] (FRIDAY) Valid? false
Please substitute your desired time zone if it didn’t happen to be America/Chihuahua. Time zone matters.
Question: Can I use java.time on Android below API level 26? How?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
One possible approach could be to normalize all your times to offsets from a chosen week starting point, say Sunday 12:00am = 0. Convert all your times into minutes since the starting point. Then simply check whether your chosen time (also converted to minutes since start) falls within any of the ranges.
I just want it to be displayed from current time adding 30mins till day ends
Ex-Today time is 09:46AM
It should display like 10:00AM,10:30AM,11:00AM....11:30PM for that particular date.
But here in my code its displaying from 00:00...23:30 for whole day.
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
int startDate = cal.get(Calendar.DATE);
while (cal.get(Calendar.DATE) == startDate) {
Log.d("time","currenttime"+cal.getTime());
cal.add(Calendar.MINUTE, 30);
}
java.time and ThreeTenABP
Duration interval = Duration.ofMinutes(30);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
ZoneId zone = ZoneId.of("Europe/Podgorica");
ZonedDateTime now = ZonedDateTime.now(zone);
// Start at a whole half hour no earlier than now
ZonedDateTime start = now.truncatedTo(ChronoUnit.HOURS);
while (start.isBefore(now)) {
start = start.plus(interval);
}
// End when a new day begins
ZonedDateTime limit = now.toLocalDate().plusDays(1).atStartOfDay(zone);
// Iterate
ZonedDateTime currentTime = start;
while (currentTime.isBefore(limit)) {
System.out.println(currentTime.format(timeFormatter));
currentTime = currentTime.plus(interval);
}
When I ran the snippet just now, I got the following output:
20:30
21:00
21:30
22:00
22:30
23:00
23:30
Of course substitute your desired time zone where I put Europe/Podgorica.
I used the following imports:
import org.threeten.bp.Duration;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;
Question: Can I use java.time on my Android API level?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26) the modern API comes built-in. In this case import from java.time with subpackages (not org.threeten.bp).
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.
Use "HH:mm" for 24 hr format and "hh:mm a" for 12 hr format
Update 1
Below is a full example that displays what you want on a textview:
TextView timeNow = findViewById(R.id.time_now);
Calendar cal, atMidnight;
//SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm a");
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
cal = Calendar.getInstance();
atMidnight = Calendar.getInstance();
atMidnight.add(Calendar.DATE, 1);
atMidnight.set(Calendar.HOUR_OF_DAY, 0);
atMidnight.set(Calendar.MINUTE, 0);
atMidnight.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, 30);
String txt = "";
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);
Update 2
To round the minutes to the next 30mins, you can do the below:
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
int unroundedMinutes = cal.get(Calendar.MINUTE);
int mod = unroundedMinutes % 30;
cal.add(Calendar.MINUTE, 30-mod);
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);
I am taking current date using the code like below
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
And I am selecting date using
CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth)
String s = +year + " : " + (month + 1) + " : " +dayOfMonth ;
and passing it on next activity as--
Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);
I want to check here if user selected previous date from current date
then give a message and don't go on next activity.
Use SimpleDateFormat:
If your date is in 31/12/2014 format.
String my_date = "31/12/2014"
Then you need to convert it into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (new Date().after(strDate)) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
or
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (System.currentTimeMillis() > strDate.getTime()) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
I am providing the modern answer.
java.time and ThreeTenABP
Use LocalDate from java.time, the modern Java date and time API.
To take the current date
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
System.out.println(currentDate);
When I ran this code just now, the output was:
2020-01-05
To get selected date in your date picker
int year = 2019;
int month = Calendar.DECEMBER; // but don’t use `Calendar`
int dayOfMonth = 30;
LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth);
System.out.println(selectedDate);
2019-12-30
Your date picker is using the same insane month numbering that the poorly designed and long outdated Calendar class is using. Only for this reason, in an attempt to produce readable code, I am using a constant from that class to initialize month. In your date picker you are getting the number given to you, so you have no reason to use Calendar. So don’t.
And for the same reason, just as in your own code I am adding 1 to month to get the correct month number (e.g., 12 for December).
Is the date in the past?
if (selectedDate.isBefore(currentDate)) {
System.out.println("" + selectedDate + " is in the past; not going to next activity");
} else {
System.out.println("" + selectedDate + " is OK; going to next activity");
}
2019-12-30 is in the past; not going to next activity
Converting to String and back
If you need to convert your selected date to a string in order to pass it through the Intent (I don’t know whether this is a requirement), use the toString and parse methods of LocalDate:
String dateAsString = selectedDate.toString();
LocalDate recreatedLocalDate = LocalDate.parse(dateAsString);
System.out.println(recreatedLocalDate);
2019-12-30
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Use below code,
Create a date object using date formator.
Compare date (There many way out to compare dates and one is mentioned here)
Open intent or make toast as you said message.
CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
String s = (month + 1) + "-" + dayOfMonth + "-" + year;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date dateSource = null;
Calendar cal = Calendar.getInstance();
Date sysDate = cal.getTime();
try {
dateSource = sdf.parse(s);
if(dateSource.compareTo(sysDate)>0){
Toast.makeToast("Selected worng date",Toast.SHOW_LONG).show();
}else{
Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);
}
}
catch (ParseException e) {
Loger.log("Parse Exception " + e);
e.printStackTrace();
}
}
}
Edit
You need a view xml having the calender defined in it. It can be a fragment or activity view xml file
Inflate the view in your Activity or fragment class.
View _rootView = inflater.inflate({your layout file},container, false);
Get the respective control java object from the xml like
cal = (CalendarView)_rootView.findViewById(R.id.calViewId);
Now call event listener on this cal object.
Try this lines of code, this may help. Cheers!!!
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(enteredDate);
if (System.currentTimeMillis() > date.getTime()) {
//Entered date is backdated from current date
} else {
//Entered date is updated from current date
}
} catch (ParseException e) {
e.printStackTrace();
}
I have time in milliseconds, now I want to separate time and date from these milliseconds.
how can i do this???
you can use like this
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliseconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
This function will give you a String date from milliseconds
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds)
{
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat("MMM d, yyyy").format(date);
return formattedDate;
}
Convert the milliseconds to Date instance and pass it to the chosen formatter:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String myDate = dateFormat.format(new Date(dateInMillis)));
Use a Calendar to get the values of different time fields:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int monthOfYear = cal.get(Calendar.MONTH);
You could convert the milliseconds to a date object and then extract date in the format of a time string and another string of just the date
Further to Kiran Kumar Answer
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds, String dateStyle){
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat(dateStyle).format(date);
return formattedDate;
}
java.time and ThreeTenABP
I suggest java.time, the modern Java date and time API, for your date and time work:
long millisecondsSinceEpoch = 1_567_890_123_456L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date: " + date);
System.out.println("Time: " + time);
Output in my time zone (Europe/Copenhagen):
Date: 2019-09-07
Time: 23:02:03.456
The date and time classes used in the other answers — Calendar, Date and SimpleDateFormat — are poorly designed and long outdated. This is why I don’t recommend using any of them but prefer java.time.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You can use the Date format and set your millisecond value as a parameter to this constructor, Follow this code:
SimpleDateFormat SDF= new SimpleDateFormat("dd/MM/yyyy");
String date = SDF.format(new Date(millies)));
I've tried different methods around the web but couldn't make it work.
Cursor cursor = sqlite.myDataBase.rawQuery("SELECT StartDate, EndDate FROM Tracks Where Id="+'"'+trackId+'"',null);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("StartDate")));
Date endDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("EndDate")));
In this way I get both dates in good format. Now I want to find the difference between EndDate and Startdate in seconds.
Any advice? Thank you.
You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
Edit:
-Corrected the name of the variable diffInMs which was written diffInM(i)s in the second line.
try below method:-
public String twoDatesBetweenTime(String oldtime)
{
// TODO Auto-generated method stub
int day = 0;
int hh = 0;
int mm = 0;
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = dateFormat.parse(oldtime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
}
catch (ParseException e)
{
e.printStackTrace();
}
if(day==0)
{
return hh + " hour " + mm + " min";
}
else if(hh==0)
{
return mm + " min";
}
else
{
return day + " days " + hh + " hour " + mm + " min";
}
}
Just complementing this answer for other developers (like me) who are using Time instead of Date.
Time t1 = new Time();
t1.setToNow();
Thread.sleep(1000);
Time t2 = new Time();
t2.setToNow();
diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true));
While the other answers work and were fine answers in 2010, I am providing the modern answer.
java.time and ThreeTenABP
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
ZoneId zone = ZoneId.systemDefault();
String startDateString = "2019-12-31 23:34:45";
String endDateString = "2020-01-01 07:56:34";
ZonedDateTime start = LocalDateTime.parse(startDateString, formatter).atZone(zone);
ZonedDateTime end = LocalDateTime.parse(endDateString, formatter).atZone(zone);
long diffSeconds = ChronoUnit.SECONDS.between(start, end);
System.out.println("Difference: " + diffSeconds + " seconds");
In most time zones output from this snippet will be:
Difference: 30109 seconds
I am using ZonedDateTime because it takes transitions to and from summer time (DST) and other time anomalies into account. It requires that you use the correct time zone, of course. If the time zone setting of your device is changed since you stored the dates and times into your database, you risk some surprises. To prevent such, you may store a UTC offset along with your times and then parse them into OffsetDateTime on retrieval.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.