how to get date from milliseconds in android - 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)));

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.

Time without date

I get time with time zone (without date component) from a PostgreSQL server in json like this { "time": "03:00:00+01" }. How do I handle this in Android? Is there any structure which can hold just time without date? Or converting it to the epoch Date representation i.e. Thu Jan 01 03:00:00 GMT+01:00 1970 is the only good solution?
OffsetTime from java.time and ThreeTenABP
An OffsetTime is a time of day without date and with an offset from UTC. It thus very precisely models the information in your string from JSON. So I would clearly prefer it over Date. Also because the Date class is poorly designed and long outdated.
String timeStringFromJson = "03:00:00+01";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ssX");
OffsetTime parsedTime = OffsetTime.parse(timeStringFromJson, timeFormatter);
System.out.println("Parsed time: " + parsedTime);
Output from this snippet is:
Parsed time: 03:00+01:00
As a detail that may or may not matter to you, the offset from the string is retained, contrary to what Date can do because a Date hasn’t got a time zone or offset.
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 parse your date into a Date object using the SimpleDateFormat with the following pattern:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
try
{
Date date = format.parse("03:00:00+01", Locale.getDefault());
Log.d( "debugDate", " date is: " + date );
}
catch (ParseException e)
{
e.printStackTrace();
}
Output:
Thu Jan 01 03:00:00 GMT+01:00 1970
In case your date structure become "03:00:00+01:00", you need to use this pattern :
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ssZ", Locale.getDefault());
Output:
Thu Jan 01 03:00:00 GMT+01:00 1970
You can convert the String timestamp to the milliseconds since Epoch as a long value, then store/retrieve the long value and convert it back to a String timestamp as done below in main.
I'm assuming the +01 in your example is for Central European Time.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class SDFTest {
/**
Global SimpleDateFormat
*/
private static SimpleDateFormat sdf = null;
public static void main(String[] args) {
// Initialize the Simple Date Format;
sdf = new SimpleDateFormat("HH:mm:ssX");
// Ignore this if you need timestamps converted to your local TimeZone;
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
// Say this is the supplied time String;
String suppliedDate = "03:00:00+01";
// Convert from String timestamp to long;
long convertedToTimeStamp = getTimeStamp(suppliedDate);
System.out.println(suppliedDate + " => " + convertedToTimeStamp + "ms");
// Convert from long timestamp to String;
String convertedBackToString = getDateString(convertedToTimeStamp);
System.out.println(convertedToTimeStamp + "ms => " + convertedBackToString);
}
/**
Converts String timestamp to the number of milliseconds since Epoch.
*/
private static long getTimeStamp(String date_str) {
try {
Date date = sdf.parse(date_str);
return date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
Converts long timestamp to String
*/
private static String getDateString(long timestamp) {
try {
Date date = new Date(timestamp);
return sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Output:
As the Date component is not present in the suppliedDate it won't ever matter.

How to display time adding 30mins from current time

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

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