How to get difference between two calendar times - android

I want to get the two calender time difference
my calender is
val calendar1 = Calendar.getInstance()
calendar1[Calendar.HOUR+1] = hour.toString().toInt()
calendar1[Calendar.MINUTE] = minute.toString().toInt()
this is giving in 12 hours format Wed Nov 17 06:30:31 GMT+05:30 2021
current calender is:-
val calendar = Calendar.getInstance()
calendar[Calendar.HOUR]=calendar.get(Calendar.HOUR)
calendar[Calendar.MINUTE]=calendar.get(Calendar.MINUTE)
this is giving in 24 hours format Wed Nov 17 18:01:32 GMT+05:30 2021
how to get this calender in 12 hours format
thats why im having difficult in finding two calender difference
can anyone help?

In first calender you are using
calendar1[Calendar.HOUR+1] -> which will be equivalent to calendar1[Calendar.HOUR_OF_DAY]
Here are the constants from Calendar class
public static final int HOUR = 10;
public static final int HOUR_OF_DAY = 11;
use calendar1[Calendar.HOUR] for 24 hour format .
Better way is to get millis from both calenders and find difference between 2 millis .
To get millis use calendar.time.time
for getting difference between millis see this answer

Related

Midnight Time zone conversion

I'm trying to convert midnight of one timezone to midnight of another time zone. Kotlin pretty much made it easy for the conversion of time zones but it does not work the same way when converting date and time to milliseconds.
Problem:
Indian Time: Mon Sep 28 00:00:00 GMT+5:30 2020
Vancouver Time: Sunday Sep 27 11:30:00 GMT-7:00 2020
What I need
Indian Time: Mon Sep 28 00:00:00 GMT+5:30 2020
Vancouver Time: Sunday Sep 27 11:30:00 GMT-7:00 2020
Here is what I tried:
val today = DateTime().withTimeAtStartOfDay().toDate() //current date and time converted to Date format
val dateOutputFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") // formatting the output as SimpleDateFormat
dateOutputFormat.setTimeZone(TimeZone.getTimeZone("America/Vancouver")) //Setting the timezone
Log.d("Datey2", "Before conversion ${today}") // Before conversion Mon Sep 28 00:00:00 GMT+5:30 2020
val Vancouver = Date(dateOutputFormat.format(today)).time //formatting the timezone
Log.d("Datey2", "After conversion $Vancouver") // After conversion Sun Sep 27 11:30:00 GMT+05:30 2020
val VancouverMnight = DateTime(Vancouver).withTimeAtStartOfDay().millis
Log.d("Datey2", "MidNight $VancouverMnight") // MidNight Sun Sep 27 00:00:00 GMT+05:30 2020
Output:
Before conversion Mon Sep 28 00:00:00 GMT+5:30 2020
After conversion Sun Sep 27 11:30:00 GMT+05:30 2020 // Note the GMT+5:30 in vacouver time
MidNight Sun Sep 27 00:00:00 GMT+05:30 2020
Then I convert these into milliseconds as follows
Log.d("Datey2", "After conversion {$VancouverMnight.time}") // using time function gives output in milliseconds
But when I convert those Vancouver outputs to milliseconds, I get the following:
1601186400000 // Sep 26 23:00:00 2020 - Goes 2 days before the given time
1601145000000 // Sep 26 11:30:00 2020
What I need:
Sep 27 11:30:00 2020
Sep 27 00:00:00 2020 (I need these in milliseconds)
Since you are using Joda-Time, I recommend you either stick to that or move on to java.time, the modern Java date and time API. Stay away from Date and SimpleDateFormat. They are poorly designed and long outdated, and there is absolutely no reason why you should want to touch them.
For a Joda-Time solution in Java because this is what I can write and run:
DateTimeZone vancouverTimeZone = DateTimeZone.forID("America/Vancouver");
DateTimeFormatter dateOutputFormat = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss")
.withZone(vancouverTimeZone);
DateTime today = new DateTime().withTimeAtStartOfDay();
System.out.println("Today: " + today);
System.out.println("Today as seen in Vancouver: " + today.toString(dateOutputFormat));
long millisBeforeConversion = today.getMillis();
System.out.println("Millis before conversion: " + millisBeforeConversion);
DateTime vancouverMidnight = today.withZone(vancouverTimeZone)
.withTimeAtStartOfDay();
long millisAfterConversion = vancouverMidnight.getMillis();
System.out.println("Millis after conversion: " + millisAfterConversion);
Output when running today in Asia/Kolkata time zone:
Today: 2020-09-29T00:00:00.000+05:30
Today as seen in Vancouver: 2020/09/28 11:30:00
Millis before conversion: 1601317800000
Millis after conversion: 1601276400000
A day has passed since you asked your questions, so you cannot compare the millisecond values from my output with your own from the question, but you can verify that they agree with what you would want for today (already September 29 in India).
Note that the count of milliseconds since the epoch is independent of time zone. So whether you get the milliseconds before or after conversion to America/Vancouver time zone makes no difference.
If you want to move on to java.time, follow the good answer by Arvind Kumar Avinash.
The problem is that you are trying to write the java.util.Date object directly which outputs the value of java.util.Date#toString. Note that a date-time object is supposed to store the information about date, time, time-zone etc. but not about the formatting. The java.util.Date object is not a real date-time object like the modern date-time classes; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have time-zone information, it applies the time-zone of your JVM and displays the same. If you need to print the date-time in a different time-zone, you will need to set the time-zone to SimpleDateFormat and obtain the formatted string from it e.g.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ssZ z");
Date date = new Date();
// Date and time in India
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
// Output to be written to the log file
System.out.println(sdf.format(date));
// Date and time in Vancouver
sdf.setTimeZone(TimeZone.getTimeZone("America/Vancouver"));
// Output to be written to the log file
System.out.println(sdf.format(date));
}
}
Output:
2020/09/29 17:57:06+0530 IST
2020/09/29 05:27:06-0700 GMT-07:00
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time. If your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ssZ z");
// Date and time in India
ZonedDateTime zdtNowIST = LocalDate.now().atStartOfDay((ZoneId.of("Asia/Calcutta")));
// Output in the default format
System.out.println(zdtNowIST);
// Output in the custom format
System.out.println(zdtNowIST.format(dtf));
// Date and time in Vancouver
ZonedDateTime zdtNowVancouver = zdtNowIST.withZoneSameInstant(ZoneId.of("America/Vancouver"));
// Output in the default format
System.out.println(zdtNowVancouver);
// Output in the custom format
System.out.println(zdtNowVancouver.format(dtf));
}
}
Output:
2020-09-29T00:00+05:30[Asia/Calcutta]
2020/09/29 00:00:00+0530 IST
2020-09-28T11:30-07:00[America/Vancouver]
2020/09/28 11:30:00-0700 GMT-07:00
I do not know Kotlin but I believe you should be able to use Java code directly in Kotlin. If not, at least you should be able to convert it using Kotlin syntax.

Data integrity violated in function "set" of class GregorianCalendar

I'am using GregorianCalendar class to manipulate with date and time.
I need to get only a current date without time.
My code:
Calendar today = new GregorianCalendar();
today.set(GregorianCalendar.HOUR,0);
today.set(GregorianCalendar.MINUTE,0);
today.set(GregorianCalendar.SECOND,0);
today.set(GregorianCalendar.MILLISECOND,0);
Date todayDate = new Date();
todayDate.setTime(today.getTime().getTime());
I expect todayDate will be like this "Wed Dec 07 00:00:00 EET 2016"
But actually todayDate is "Wed Dec 07 12:00:00 EET 2016".
Which is the correct way to do it?
Ia understend difference between fields HOUR and HOUR_OF_DAY when I get value, but why when I set value of HOUR to "0" the HOUR_OF_DAY is not seting to "0" automatically. Zero is always zero...
Question is about Data integrity...
It is a mistake to thought zero is always zero... It is not true for hours after midday. Zero hours after midday in short form (am/pm) is 12 hours in 24 form.
Thanks to #selvin

day differences using Calendar in java

I am using Calendar Class in my android app to calulate day of year of a date and then do some comparison with current day of year. Here is the code I use :
Date now=new Date();
Calendar ca1 = Calendar.getInstance();
ca1.set(now.getYear(), now.getMonth(), now.getDate());
int nowC=ca1.get(Calendar.DAY_OF_YEAR);
//Date arg0=say,get from user
Calendar ca2 = Calendar.getInstance();
ca2.set(arg0.GetBirthDay().getYear(),arg0.GetBirthDay().getMonth(),arg0.GetBirthDay().getDate());
int d1C=ca2.get(Calendar.DAY_OF_YEAR);
I debug my application and I see the following value for current day :
Fri Mar 02 14:18:33 Asia/Tehran 2012
and for arg0:
Fri Mar 02 00:00:00 Asia/Tehran 1979
And 'nowC' got 62, and 'd1C' got 61.
I expect them to be equal cause both of them has same month and day, also If I use DateTime class of joda package, as below, I get the same results:
int ndy=dtnow.getDayOfYear();
int d1dy=dt1.getDayOfYear();
Why it is happening ?
2012 was a leap year, 1979 was not. There is an extra day before March 2nd this year - so both APIs are giving you the right answer!
I suspect you want to compare both the month and day-of-month, to get the semantics you are expecting.

Calendar dayOfMonth off by 1

When trying to get a string for the current date using
DateFormat.getDateInstance().format(calendar.getTime())
it keeps returning the wrong day. For example, it is saying today, July 25th., is July 26th. Also when I use it to sat a date picker, I get the day value by using
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
When the date picker is set, it also shows the day ahead by 1.
To get the calendar I'm using
Calendar calendar = Calendar.getInstance();
Is there something I'm missing?
Thanks
I would imagine this is because you havent set the timezone to your timezone, and rather than the day being off randomly, the time zone you are in is diferent than GMT (Greenwich Median? Time). Try looking at this example How to handle calendar TimeZones using Java?

GregorianCalendar / Calendar and setting the HOUR field oddity

I'm trying to create a 'fixed' time (midnight in 24 hour clock format, i.e., 00:00:00) to set as a string for a SQL SELECT query using the the following...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar todayDate = new GregorianCalendar();
Log.d(TAG, "todayDate: " + todayDate.getTime().toString());
Log.d(TAG, "formatted todayDate: " + sdf.format(todayDate.getTime()));
todayDate.clear(Calendar.HOUR);
todayDate.clear(Calendar.MINUTE);
todayDate.clear(Calendar.SECOND);
todayDate.set(Calendar.HOUR, 0);
todayDate.set(Calendar.MINUTE, 0);
todayDate.set(Calendar.SECOND, 0);
Log.d(TAG, "formatted modified todayDate: " + sdf.format(todayDate.getTime()));
This is fine UNLESS the current time is PM. For example,
todayDate: Fri Jan 28 23:34:34 GMT 2011
formatted todayDate: 2011-01-28 23:34:34
formatted modified todayDate: 2011-01-28 12:00:00 <- THE hour is 12 not 00
If I do this when the current time is between midnight and midday, (i.e., 00:00:00 -> 11:59:59 AM) then my hour in the formatted string is correctly set to 00. If I do it at any time after midday and before midnight then I get 12 for my hour and not 00.
Can anybody explain this and help me find a fix (or alternative way of doing things) please?
You need to set HOUR_OF_DAY to 0 instead of HOUR
todayDate.set(Calendar.HOUR_OF_DAY, 0);
From the API docs:
HOUR Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
HOUR_OF_DAY Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

Categories

Resources