converting long string to date [duplicate] - android

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Convert UTC Epoch to local date
(16 answers)
How to convert String to long in Java?
(10 answers)
Closed 1 year ago.
I am getting date value from DB as a long value. I am converting this to string to use parse function. Given below is my code
Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(strDate1);
But the app is crashing when this code is executing.it will successfully execute if the
strDate1="12/30/2012".
But i am having this value as "12302012235"(pzudo value).
How can i do this?
edit:
i am saving date value to DB as INTEGER. from DB i am getting this value and converting to string.this is the actual strDate1 value
strDate1="1346524199000"

Try the following code segment:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(Long.parseLong(val));
Date d = (Date) c.getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String time = format.format(d);//this variable time contains the time in the format of "day/month/year".

Try this,
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date dateD=new Date();
dateD.setTime(LongTime);
date=dateFormat.format(dateD);

Java 8, Convert milliseconds long to Date as String by given date format pattern. If you have a long milliseconds and want to convert them into date string at specifies time zone and pattern, then you can use it:-
dateInMs is a long value of DateTime.
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(Instant.ofEpochMilli(dateInMs).atZone(ZoneId.of("Europe/London")))

java.time
The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API* .
Using modern date-time API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
long input = 12302012235L;
// Get Instant from input
Instant instant = Instant.ofEpochMilli(input);
System.out.println(instant);
// Convert Instant to ZonedDateTime by applying time-zone
// Change ZoneId as applicable e.g. ZoneId.of("Asia/Dubai")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
System.out.println(zdt);
// Format ZonedDateTime as desired
// Check https://stackoverflow.com/a/65928023/10819573 to learn more about 'u'
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formatted = dtf.format(zdt);
System.out.println(formatted);
// If at all, you need java.util.Date
Date date = Date.from(instant);
}
}
Output:
1970-05-23T09:13:32.235Z
1970-05-23T10:13:32.235+01:00[Europe/London]
05/23/1970
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and 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.

You can try following code:
private Date getGMTDate(long date) {
SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
"yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat(
"yyyy-MMM-dd HH:mm:ss");
Date temp = new Date(date);
try {
return dateFormatLocal.parse(dateFormatGmt.format(temp));
} catch (ParseException e) {
e.printStackTrace();
}
return temp;
}
I hope this will help you.

Try this
Date date1 = new SimpleDateFormat("MMddyyyySSS").parse(strDate1);
Hope it will works for 12302012235 , but i assume 235 is millisec.

i got the answer.actually i wanted to convert the string to date only for comparing the values.since i am getting the value as long i directly used the compareTo function to do this.avoided the conversion of long to string and string to date conversion.thank you all for support.

Related

How do i split the date from the string of date-time with time zone?

I have a date-time string with time zone like "2019-05-21 04:49:39.000Z" this. How do i split the date from this string without split method.I have to use the time zone formatter. Anyone please help me in it.
public static String getDateTime(String created_on) {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outFormat = new SimpleDateFormat("dd MMM yyyy hh:mm aa");
try {
inFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = inFormat.parse(created_on);
outFormat.setTimeZone(TimeZone.getDefault());
created_on = outFormat.format(value);
} catch (ParseException e) {
e.printStackTrace();
}
return created_on;
}
Use this Function.It will help you to get Date and Time
Use some library for parsing String to e.g. OffsetDateTime,
after from parsedDateTime variable get any part of the time (hour, min...)
In kotlin (min API 26) :
val parsedDateTime = OffsetDateTime
.parse("2019-05-21 04:49:39.000Z", DateTimeFormatter.ISO_DATE_TIME)
val time = "${parsedDateTime.hour} : ${parsedDateTime.minute}"
check this link for more examples : examples
https://grokonez.com/kotlin/kotlin-convert-string-datetime
Update :
As Ole V.V. mentioned in comment - if you’re not yet on API level 26, you may add ThreeTenABP to your Android project and import OffsetDateTime from there (and than the same code works for lower API).

Format Date to display dd/MM/yyyy [duplicate]

This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 5 years ago.
I have a method to format date i get from the server in this format 2018-01-18T13:52:49.107Z. I want to convert this format to only show the day, month and year but it doesnt work. How do i translate this response from the server to show the date format.
This is my method below:
private String formatDate(String dateString) {
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.S" );
Date d = sd.parse(dateString);
sd = new SimpleDateFormat("dd/MM/yyyy");
return sd.format(d);
} catch (ParseException e) {
}
return "";
}
Try to change the date formate with yyyy-MM-dd'T'HH:mm:ss.SSS
private String formatDate(String dateString) {
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS" );
Date d = sd.parse(dateString);
sd = new SimpleDateFormat("dd/MM/yyyy");
return sd.format(d);
} catch (ParseException e) {
}
return "";
}
Try this
private String formatDate(String dateString) {
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
Date d = null;
try {
d = input.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
String formatted = output.format(d);
Log.i("DATE", "" + formatted);
return formatted;
}
OUTPUT
Convert input string into a date
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = inputFormat.parse(inputString);
Format date into output format
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = outputFormat.format(date);
Here is the code to achieve this:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateForm {
public static void main(String args[]) {
String formatted = convertDateToReadable("2018-01-18T13:52:49.107Z");
System.out.println("formatted = " + formatted);
}
public static String convertDateToReadable(String dateStr) {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);
DateFormat outputFormat = new SimpleDateFormat("yyyy/MM/dd");
Date formattedDate = null;
try {
formattedDate = inputFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDateStr = outputFormat.format(formattedDate);
return formattedDateStr;
}
}
Output = formatted = 2018/01/18
This is ISO-DATE time format.
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ)
Date and time is separated with a capital T.
UTC time is defined with a capital letter Z.
private String formatDate(String dateString) {
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ" );
Date d = sd.parse(dateString);
sd = new SimpleDateFormat("dd/MM/yyyy");
return sd.format(d);
} catch (ParseException e) {
}
return "";
}
TL:DR
private static final DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd/MM/yyyy");
private static String formatDate(String dateString) {
return Instant.parse(dateString)
.atZone(ZoneId.of("Pacific/Tarawa"))
.format(dateFormatter);
}
You need to specify time zone
Given your string 2018-01-18T13:52:49.107Z the method above returns 19/01/2018. 19?? Yes, when it’s 13:52 UTC it’s already the following day on the Tarawa Atoll. And since it is never the same date everywhere on Earth, you need to specify the time zone in which you want the date. So please substitute your desired time zone if it didn’t happen to be Pacific/Tarawa. For example Africa/Maputo or Asia/Sakhalin. Then you will get the date in that zone, formatted as specified. It will not always coincide with the date in the string (in this case Jan 18, 2018) because the string gives the date and time in UTC. To use the user’s time zone you may try specifying ZoneId.systemDefault(). This will use the JVM’s time zone setting. Beware that it is fragile, the setting may be changed under your feet from other parts of your program or other programs running in the same JVM. If you did intend to have the date in UTC as in the string, use:
return Instant.parse(dateString)
.atOffset(ZoneOffset.UTC)
.format(dateFormatter);
Now the result is guaranteed to be 18/01/2018.
java.time
I am using java.time, the modern Java date and time API. I recommend you do the same. The Date class is long outdated, and SimpleDateFormat is not only that, it is also notoriously troublesome. The modern API is so much nicer to work with.
Question: Can I use java.time on Android?
Yes, you can use java.time on Android. It just requires at least Java 6.
In Java 8 and later and on newer Android devices the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new 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.
What went wrong in your code?
The main error in your method (worse that using the outdated classes) is between the following two lines!
} catch (ParseException e) {
}
An empty catch block swallows exceptions so you don’t get to see what goes wrong. Never do that. Try for example:
} catch (ParseException e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Error offset: " + e.getErrorOffset());
if (e.getErrorOffset() != -1) {
System.out.println("Error text: " + dateString.substring(e.getErrorOffset()));
}
}
This prints:
Message: Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 5
Error text: 01-18T13:52:49.107Z
So your formatter cannot parse 01, the month. Check the documentation, it says about month: “ If the number of pattern letters is 3 or more, the month is interpreted as text;…”. So lets try MM instead of MMM in the format pattern string. Now we get:
Message: Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 10
Error text: T13:52:49.107Z
The T is offending. Of course, it’s not in the pattern string. To indicate that a literal letter is part of the format, enclose it apostrophes: yyyy-MM-dd'T'HH:mm:ss.S. Next time your method returns:
18/01/2018
Are we through? I’d say not. You are ignoring the Z at the end. It means offset 0 from UTC or “Zulu time zone”. By ignoring it, you are parsing the date-time string as a date-time in your JVM’s default time zone, which gives an incorrect time. In newer Java versions the Z can be parsed using the format pattern letter uppercase X, either one, two or three of them. Try yyyy-MM-dd'T'HH:mm:ss.SXXX:
Message: Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 22
Error text: 7Z
It seems that one S matches two digits, 10, but not the third decimal, 7. I don’t know why, but let’s put three, SSS for three decimals: yyyy-MM-dd'T'HH:mm:ss.SSSXXX. Now it works.
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.timeto 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.

OffsetDateTime to Date Android

I am getting an OffsetDateTime from our backend in a String format like this:
"2017-07-15T10:52:59Z"
I am trying to parse this String to a Android Date:
private SimpleDateFormat mSimpleDateFormat;
private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
mSimpleDateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN, Locale.getDefault());
Date newDate = null;
String dateString = notice.getCreated();
try {
newDate = mSimpleDateFormat.parse(dateString);
} catch (ParseException e) {
LogHelper.showExceptionLog(MyClass.class, e);
}
It always throws:
Unparseable date: "2017-07-15T10:52:59Z"
To parse the Z (which is the UTC designator) you must use the X pattern (as explained in javadoc):
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
String dateString = "2017-07-15T10:52:59Z";
Date newDate = mSimpleDateFormat.parse(dateString);
If you use just yyyy-MM-dd'T'HH:mm:ss as a pattern, SimpleDateFormat will use the system's default timezone and ignore the Z, giving incorrect results: it'll parse the date/time as 10:52 in the default timezone, which can be different to 10:52 in UTC. By using the X pattern, you get the correct result.
I also removed the Locale because this formatter is not dealing with any locale-sensitive information (like month and day of week names), so it doesn't affect the parsing in this case (and SimpleDateFormat already uses the default locale if you don't specify one).
PS: the X pattern was introduced in JDK 7. If you're using and older version, it won't be available. In this case, you can set the UTC as a timezone of the formatter:
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Obviously this code is assuming that the input is always in UTC (with Z in the end).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
For Android, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need ThreeTenABP (more on how to use it here).
As the input string is in ISO 8601 format, you can easily parse it to a org.threeten.bp.OffsetDateTime:
String dateString = "2017-07-15T10:52:59Z";
OffsetDateTime odt = OffsetDateTime.parse(dateString);
You can then convert this to a java.util.Date easily, using the org.threeten.bp.DateTimeUtils class:
Date date = DateTimeUtils.toDate(odt.toInstant());
If the input is always in UTC (always with the Z in the end), you can also use a org.threeten.bp.Instant:
String dateString = "2017-07-15T10:52:59Z";
Instant instant = Instant.parse(dateString);
Date date = DateTimeUtils.toDate(instant);
The only difference is that Instant only parses UTC inputs (ending with Z) and OffsetDateTime accepts any valid UTC offset (like -03:00 or +05:30).

Difference between two datetime formats in android?

As i am new to android development I am unable to find code for calculating the difference between two datetime formats. My question is.
I am using webservice in my project where i am getting datetime response as follows..
starttime :- [2012-11-04 10:00:00]
endtime :- [2012-11-04 12:00:00]
Here i want to display on screen as
Today Timings :- 2012-11-04 2 hours
Means need to calculate the difference between two dates and need to display the time difference on screen.
Can anyone please help me with this.
Given you know the exact format in which you are getting the date-time object, you could use the SimpleDateFormat class in Android which allows you to parse a string as a date given the format of the date expressed in the string. For your question:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime = sdf.parse(<startTime/endTime String>, 0);
Similarly parse your endtime, and then the difference can be obtained using getTime() of the individual objects.
long diff = endTime.getTime() - startTime.getTime()
Then it's as simple as converting the difference to hours using:
int hours = (int)(diff/(60*60*1000));
Hope that helps.
java.time
Solution using java.time, the modern API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
LocalDateTime startTime = LocalDateTime.parse("2012-11-04 10:00:00", dtf);
LocalDateTime endTime = LocalDateTime.parse("2012-11-04 12:00:00", dtf);
long hours = ChronoUnit.HOURS.between(startTime, endTime);
System.out.println(hours);
}
}
Output:
2
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and 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.
If you're using java.util.Date; you're gonna have to use an intermediate variable. you can convert your dates to long values and subtract those and then convert your long back to a date.
long diff = new Date().getTime() - new Date(milliseconds).getTime();
Date dateDiff = new Date(diff);
But you should be warned that it doesn't take daylight savings and whatever else variables into account. if you're that scrupulous, you might be indulged with this replacement date class. It has the functionality you seek.
I use this code to get difference of two date.
public void getTimeDifference(Date endDate,Date startDate) {
Date diff = new Date(endDate.getTime() - startDate.getTime());
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTime(diff);
int day=calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
}
}

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

Categories

Resources