How to compare current date with selected date in android with java - android

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();
}

Related

Calendar won't return date with AM/PM

I want the date in AM/PM format. Examples suggest to use a SimpleDateFormat with a or aa but this is simply not working for me.
First I set the day. Then I set view to visible for start time.
Result is format of Wed May 20 01:00:00 EDT 2020 want something like Wed May 20 01:00:00 AM EDT 2020
This applies to calendar.getTime() in the setStartTime method. The first method is only included because the day selected is linked as a global variable. Problem lies within the second method.
I could probably manually change the final date as string and convert it back but I don't want to add unnecessary complexity. I want to find out why Calendar won't succeed since this should be extremely basic.
In the end my goal is to add the date to firebase. It must be uniform across Android, IOS and Web. Therefore I need the date to be in this exact format.
Here is code:
SimpleDateFormat serviceSETimeFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm aa");
public void setStartDay(View view)
{
Calendar calendar = Calendar.getInstance();
DatePickerDialog picker = new DatePickerDialog(ServiceCreation.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
GregorianCalendar mCal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
Date dateForDisplay = mCal.getTime();
int startHourIndex = getThirdSpaceIndex(dateForDisplay.toString());
//SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
serviceSETimeFormat.setCalendar(mCal);
Date dateFormatted = null;
try{
dateFormatted= serviceSETimeFormat.parse(serviceSETimeFormat.format(mCal.getTime()));
currBaseStartDate=dateFormatted;
}
catch(ParseException p){
Log.wtf("SC","Parse exc34");
}
Log.wtf("SC","Here is orig date: "+dateFormatted);
//Don't show hh/mm/ss (these are held as 0)
startDayView.setText(dateForDisplay.toString().substring(0,startHourIndex));
startEndTimeWrapper.setVisibility(View.VISIBLE);
}
}, calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
long currentTime = new Date().getTime();
picker.getDatePicker().setMinDate(currentTime);
picker.show();
}
public void setStartTime(View view) {
TimePickerDialog mTimePicker = new TimePickerDialog(ServiceCreation.this,
android.R.style.Theme_Holo_Light_Dialog_NoActionBar, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String minuteAsS = Integer.toString(selectedMinute);
if(minuteAsS.length()==1){
minuteAsS="0"+minuteAsS;
}
if(selectedHour==0){
startTimeView.setText((selectedHour+12)+":"+minuteAsS+" AM");
}
else if(selectedHour<12){
startTimeView.setText(selectedHour+":"+minuteAsS+" AM");
}
else if(selectedHour==12){
startTimeView.setText((selectedHour)+":"+minuteAsS+" PM");
}
else{
startTimeView.setText((selectedHour-12)+":"+minuteAsS+" PM");
}
(findViewById(R.id.endTimeWrapper)).setVisibility(View.VISIBLE);
Calendar calendar = new GregorianCalendar();
calendar.setTime(currBaseStartDate);
calendar.set(Calendar.MINUTE, selectedMinute);
Log.wtf("SC","Hour before condition: "+selectedHour);
if(selectedHour>=12){
if(selectedHour!=12){
Log.wtf("SC","Decrementing hour");
selectedHour-=12;
}
Log.wtf("SC","Hour set: "+selectedHour);
calendar.set(Calendar.AM_PM,Calendar.PM);
calendar.set(Calendar.HOUR_OF_DAY,selectedHour);
}
else{
calendar.set(Calendar.AM_PM,Calendar.AM);
calendar.set(Calendar.HOUR_OF_DAY,selectedHour);
}
startTime=calendar.getTime();
Log.wtf("SC","Here is orig start time: "+startTime);
try{
startTime=serviceSETimeFormat.parse(serviceSETimeFormat.format(startTime));
Log.wtf("SC","Here is parsed start time: "+startTime);
}
catch(ParseException e){
Log.wtf("SC","START DATE PARSE EXCEPTION");
}
}
}, 12, 0, false);
mTimePicker.setTitle("Select Start Time: ");
mTimePicker.show();
}
Three points:
Even on Android and even on API levels under 26 consider using java.time, the modern Java date and time API. Calendar, GregorianCalendar, SimpleDateFormat and Date are confusing, poorly designed and long outdated classes. The modern API is so much nicer to work with.
You don’t want a Calendar or Date with AM or PM. You want to keep your model and your presentation to the user separate. In the model you want a LocalDateTime or other appropriate date-time object, and you don’t want to worry about its format, whether it uses a 12 hours or 24 hours clock. For display to your user you want date and time in a string in an appropriate format for you user, including AM or PM. This is also why your views have a setText method and no setDate method.
No Date with AM/PM format can exist. You are asking the impossible.
java.time and ThreeTenABP
Construct a LocalDate object from your three integers for year, month and day:
int year = 2020;
int monthOfYear = Calendar.MAY; // Don’t use Calendar, though
int dayOfMonth = 11;
LocalDate date = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
System.out.println(date);
Output:
2020-05-11
I believe that your date picker numbers months from 0 for January through 11 for December. So we need to add 1 to the month number to convert to the way humans and LocalDate number months. I am only using the constant from the Calendar class to initialize the variable to a 0-based month number, don’t do it in your code since the value comes from the data picker. Calendar uses the same insane numbering.
To display the date back to the user format it into a string using a formatter:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String dateForDisplay = date.format(dateFormatter);
System.out.println(dateForDisplay);
May 11, 2020
Give the appropriate locale, or leave out the call to withLocale() to rely on the locale setting of the device.
When the user selects the time:
int selectedHour = 1;
int selectedMinute = 0;
LocalTime selectedTime = LocalTime.of(selectedHour, selectedMinute);
LocalDateTime dateTime = date.atTime(selectedTime);
System.out.println(dateTime);
2020-05-11T01:00
The time can be formatted in a way that is very similar to what we did with the date:
DateTimeFormatter timeFormatter = DateTimeFormatter
.ofLocalizedTime(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String timeForDisplay = selectedTime.format(timeFormatter);
System.out.println(timeForDisplay);
1:00:00 AM
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
My thorougher answer to a similar question: want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format
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.

How to set Calendar according to Timezone

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();
}
}

how to get date from milliseconds in android

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)));

Date formatting based on user locale on android

I want to display a date of birth based on the user locale. In my application, one of my fields is the date of birth, which is currently in the format dd/mm/yyyy. So if the user changes his locale, the date format should also change accordingly. Any pointers or code samples would really help me to overcome the problem.
You can use the DateFormat class that formats a date according to the user locale.
Example:
String dateOfBirth = "26/02/1974";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = sdf.parse(dateOfBirth);
} catch (ParseException e) {
// handle exception here !
}
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
String s = dateFormat.format(date);
You can use the different methods getLongDateFormat, getMediumDateFormat depending on the level of verbosity you would like to have.
While the accepted answer was correct when the question was asked, it has later become outdated. I am contributing the modern answer.
java.time and ThreeTenABP
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
LocalDate dateOfBirth = LocalDate.of(1991, Month.OCTOBER, 13);
String formattedDob = dateOfBirth.format(dateFormatter);
System.out.println("Born: " + formattedDob);
It gives different output depending on the locale setting of the JVM (usually taking from the device). For example:
Canadian French: Born: 91-10-13
Chinese: Born: 1991/10/13
German: Born: 13.10.91
Italian: Born: 13/10/91
If you want a longer format, you may specify a different format style. Example outputs in US English locale:
FormatStyle.SHORT: Born: 10/13/91
FormatStyle.MEDIUM: Born: Oct 13, 1991
FormatStyle.LONG: Born: October 13, 1991
FormatStyle.FULL: Born: Thursday, October 13, 1991
Question: Can I use java.time on Android?
DateTimeFormatter.ofLocalizedDate requires Api O minimum.
Yes, java.time works nicely on older and newer Android devices. No, it does not require API level 26 or Oreo even though a message in your Android Studio might have you think that. 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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Question: Can I also accept user input in the user’s local format?
Yes, you can. The formatter can also be used for parsing a string from the user into a LocalDate:
LocalDate date = LocalDate.parse(userInputString, dateFormatter);
I suggest that you first format an example date and show it to the user so that s/he can see which format your program expects for his/her locale. As example date take a date with day of month greater than 12 and year greater than 31 so that the order of day, month and year can be seen from the example (for longer formats the year doesn’t matter since it will be four digits).
Parsing will throw a DateTimeParseException if the user entered the date in an incorrect format or a non-valid date. Catch it and allow the user to try again.
Question: Can I do likewise with a time of day? A date and time?
Yes. For formatting a time of day according to a user’s locale, get a formatter from DateTimeFormatter.ofLocalizedTime. For both date and time together use one of the overloaded versions of DateTimeFormatter.ofLocalizedDateTime.
Avoid the DateFormat, SImpleDateFormat and Date classes
I recommend you don’t use DateFormat, SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead use LocalDate, DateTimeFormatter and other classes from java.time, the modern Java date and time API.
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).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
As simple as
For date + time:
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.getDefault());
For just date:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
Android api provide easy way to display localized date format.
The following code works.
public class FileDateUtil {
public static String getModifiedDate(long modified) {
return getModifiedDate(Locale.getDefault(), modified);
}
public static String getModifiedDate(Locale locale, long modified) {
SimpleDateFormat dateFormat = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
dateFormat = new SimpleDateFormat(getDateFormat(locale));
} else {
dateFormat = new SimpleDateFormat("MMM/dd/yyyy hh:mm:ss aa");
}
return dateFormat.format(new Date(modified));
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getDateFormat(Locale locale) {
return DateFormat.getBestDateTimePattern(locale, "MM/dd/yyyy hh:mm:ss aa");
}
}
You can check following code.
String koreaData = FileDateUtil.getModifiedDate(Locale.KOREA, System.currentTimeMillis());
String franceData = FileDateUtil.getModifiedDate(Locale.FRENCH, System.currentTimeMillis());
String defaultData = FileDateUtil.getModifiedDate(Locale.getDefault(), System.currentTimeMillis());
String result = "Korea : " + koreaData + System.getProperty("line.separator");
result += "France : " + franceData + System.getProperty("line.separator");
result += "Default : " + defaultData + System.getProperty("line.separator");
tv.setText(result);
To change the date format according to the locale, the following code worked to me:
String dateOfBirth = "26/02/1974";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = sdf.parse(dateOfBirth);
} catch (ParseException e) {
// handle exception here !
}
String myString = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
Then when you change the locale, the date format will change based on it.
For more information about the dates patterns:
http://docs.oracle.com/javase/tutorial/i18n/format/dateFormat.html
To get the date format pattern you can do :
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
After that, you can format your input as per the pattern.
The simple way to do it:
String AR_Format = "dd-mm-yyyy";
String EN_Format = "mm-dd-yyyy";
String getFomattedDateByLocale(Date date, String locale) {
return new SimpleDateFormat(strDateFormat, new Locale(locale)).format(date);
}
And then call it like this:
txtArabicDate.setText(getFomattedDateByLocale(new Date(), AR_Format));
txtEnglishDate.setText(getFomattedDateByLocale(new Date(), EN_Format));
Don't forget to replace new Date() by your own date variable.
Good luck.
My way, with example: UTC iso format String to android User.
//string UTC instant to localDateTime
String example = "2022-01-27T13:04:23.891374801Z"
Instant instant = Instant.parse(example);
TimeZone timeZone = TimeZone.getDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, timeZone.toZoneId());
//localDateTime to device culture string output
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String strDate = localDateTime.toLocalDate().format(dateFormatter);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
String strTime = localDateTime.toLocalTime().format(timeFormatter);
//strings to views
txtDate.setText(strDate);
txtTime.setText(strTime);

Android difference between two dates in seconds

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.

Categories

Resources