I am getting date time from rest api as like this "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?
I have tried by this way
String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Log.d("testDate",formattedDate);
} catch (ParseException e) {
e.printStackTrace();
Log.d("testDate",e.toString());
}
But getting the error
java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"
Use yyyy-MM-dd'T'HH:mm:ss.SS as format instead of yyyy-MM-dd'T'HH:mm:ss'Z'
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
java.time
You can also achieve this with java.time, the modern Java date and time API because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues:
String sourceDateTime = "2020-02-13T16:57:13.04";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SS").withZone(DateTimeZone.UTC);
LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTime, dateTimeFormatter);
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
System.out.println(localDate.toString() + " -> " + localTime.toString());
//Output should be: 2020-02-13 -> 16:57:13.040
Question: Can I use java.time on Android?
From Android 8.0 (API level 26) the modern API comes built-in.
For older android version, you can use ThreeTenABP, Android edition of ThreeTen Backport
SimpleDateFormat cannot parse your date-time string correctly.
SimpleDateFormat is notoriously troublesome and long outdated. Neither for this nor for any other purpose should you use it. Instead just use the LocalDateTime class from java.time, the modern Java date and time API. It parses your string wothout any explicit formatter.
You can’t with SimpleDateFormat
Your string has two decimals on the second of minute, .04, signifying 4 hundredths of a second. SimpleDateFormat only supports exactly three decimals on the seconds, not two or four or any other number. So there is no way that it can parse your string correctly.
java.time
It seems that you are assuming that the string you parse is in UTC and you want to convert it to the default time zone of your device. Your string is in ISO 8601 format, the format that the classes of java.time parse as their default, so we don’t need to specify any formatter.
String dateStr = "2020-02-13T16:57:13.04";
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
ZonedDateTime inDefaultTimeZone = dateTime.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault());
System.out.println(inDefaultTimeZone);
On my computer in Europe/Copenhagen time zone the output from this snippet is:
2020-02-13T17:57:13.040+01:00[Europe/Copenhagen]
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.
Wikipedia article: ISO 8601
Take out the 'Z' on your format string
This should work:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Or if you want to keep the milliseconds then use SS:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Related
getting wrong results after converting 12hrs time format to utc.
String inputPa = "hh:mm a";
String OutPa = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat inputPatter = new SimpleDateFormat(inputPa);
SimpleDateFormat outputPatter = new SimpleDateFormat(OutPa);
Date date1 = null;
String str1 = null;
try {
date1 = inputPatter.parse(txtStartTime.getText().toString());
str1 = outputPatter.format(date1);
Log.d("mycheck", str1);
} catch (ParseException e) {
e.printStackTrace();
}
java.time and ThreeTenABP
I assumed you wanted today’s date in your time zone.
String inputPa = "hh:mm a";
DateTimeFormatter timeFormatter12Hours = DateTimeFormatter.ofPattern(inputPa, Locale.ENGLISH);
ZoneId zone = ZoneId.of("America/Detroit");
String timeString = "11:34 AM";
LocalTime time = LocalTime.parse(timeString, timeFormatter12Hours);
Instant inst = LocalDate.now(zone).atTime(time).atZone(zone).toInstant();
System.out.println(inst);
Output from this example is:
2020-05-30T15:34:00Z
I would not bother converting the Instant to a string explicitly. It prints in UTC in your desired format when you print it, thus implicitly invoking its toString method (the format is ISO 8601, the international standard).
Please fill in your desired time zone. To rely on the device’ time zone setting set zone to ZoneId.systemDefault().
I am of course happy to use java.time, the modern Java date and time API. You can do that on your Android version too, see the details below.
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.
Wikipedia article: ISO 8601
public tring getCurrentUTC(Date time) {
SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
You can use this code to get current UTC time.
For you question, you just need convert the time string to the Date format.
How to get name day name like (Wednesday - Thursday) from this date format "Wed Jan 30 00:00:00 GMT+02:00 2019"
java.time
It seems that what you’ve got is an instance of the java.util.Date class. That’s a poorly designed class that is long outdated, so first thing is to see if you can avoid that and have an instance of a class from java.time, the modern Java date and time API, instead.
However, if you got the Date from a legacy API that you cannot change or don’t want to change just now, first thing is to convert it to a modern Instant and then perform further conversions from there. The following snippet uses ThreeTenABP, more on that below.
Date yourOldfashionedDate = getFromLegacyApi();
Instant modernInstant = DateTimeUtils.toInstant(yourOldfashionedDate);
String dayName = modernInstant.atZone(ZoneId.systemDefault())
.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("Day name is " + dayName);
Output given the date from your question:
Day name is Wednesday
If what you got was a String (probably a string returned from Date.toString at some point), you need to parse it first:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
String dateString = "Wed Jan 30 00:00:00 GMT+02:00 2019";
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, dateFormatter);
String dayName = dateTime.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
You see that the last bit is exactly like before.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. Only in this case use yourOldfashionedDate.toInstant() instead of DateTimeUtils.toInstant(yourOldfashionedDate).
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You can use SimpleDateFormat for it and the format part that gives you the full day name is EEEE.
Hope it helps!
You will need to first parse your String into a Calendar object using a SimpleDateFormat :
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
try {
cal.setTime(sdf.parse("Wed Jan 30 00:00:00 GMT+02:00 2019"));
} catch (ParseException e) {
// Log invalid date format
}
Then extract the day from your Calendar object:
String day = cal.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.LONG,Locale.ENGLISH);
## Here, I have attached a method that will give you expected output ##
public void dayName(){
String weekDay,time;
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE MMM dd HH:mm", Locale.US);
SimpleDateFormat dayFormat1 = new SimpleDateFormat("hh:mm yyyy", Locale.US);
dayFormat.setTimeZone(TimeZone.getTimeZone("ITC"));
dayFormat1.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar calendar = Calendar.getInstance();
weekDay = dayFormat.format(calendar.getTime());
time=dayFormat1.format(calendar.getTime());
Log.e(TAG, "dayName: "+weekDay+" GMT+"+time );// out put looks like : Tuesday Jan 29 17:58 GMT+05:58 2019
}
I have used two TimeZone are ITC and GMT
So my app fetches from information from a JSON file from a server, of which there are a few date/time values. The time and date are in UTC. I need to display these in my app, in the users local timezone.
Example of the data from JSON:
"start":"2018-10-20 03:00:00","finish":"2018-10-20 05:00:00"
My code so far, which display the date and time fine, in UTC..
val dateStringStart = radioScheduleDMList.get(position).start
val dateStringEnd = radioScheduleDMList.get(position).finish
val date = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).parse(dateStringStart)
val dateEnd = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).parse(dateStringEnd)
val day = SimpleDateFormat("d MMM").format(date)
val startDate = SimpleDateFormat("ha").format(date)
val endDate = SimpleDateFormat("ha").format(dateEnd)
How can I go about displaying this data using the devices timezone? I've been googling for hours.
Using the above example, my app shows "20 OCT" for the date, and "3AM-5AM" for the time. In my case, I live in Australia (GMT+10) so I would expect day "20 OCT" and "1PM-3PM". In short, I want to detect the user’s timezone offset from UTC and apply it for display.
java.time and ThreeTenABP
DateTimeFormatter jsonFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d MMM", Locale.forLanguageTag("en-AU"));
DateTimeFormatter hourFormatter
= DateTimeFormatter.ofPattern("ha", Locale.forLanguageTag("en-AU"));
ZoneId zone = ZoneId.systemDefault();
String dateStringStart = "2018-10-20 03:00:00";
OffsetDateTime startDateTime = LocalDateTime.parse(dateStringStart, jsonFormatter)
.atOffset(ZoneOffset.UTC);
ZonedDateTime userStartDateTime = startDateTime.atZoneSameInstant(zone);
String startDayString = userStartDateTime.format(dateFormatter);
String startTimeString = userStartDateTime.format(hourFormatter);
System.out.println("Start day: " + startDayString);
System.out.println("Start hour: " + startTimeString);
I’m sorry I don’t write Kotlin. Can you translate from Java on your own? When I run the above code on a JVM with default time zone Australia/Brisbane it outputs:
Start day: 20 Oct
Start hour: 1PM
Just do similarly for the end date and time.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the 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.
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.
im trying to convert a string(with unix timestamp) to an date with the format ( dd-MM-yyyy)
and this is working partly. The problem im having now is that my date is in 17-01-1970 (instead of march 16 2015)
im converting it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = null;
int dateMulti = Integer.parseInt(Date);
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(dateMulti);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
Log.d("test",date);
try {
d = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
where Date = 1427101853
and the result = 17-01-1970
what am i doing wrong?
You are using the wrong format string in the first line:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
mm is minutes. Use MM (months) instead.
edit A Unix timestamp is a number of seconds since 01-01-1970 00:00:00 GMT. Java measures time in milliseconds since 01-01-1970 00:00:00 GMT. You need to multiply the Unix timestamp by 1000:
cal.setTimeInMillis(dateMulti * 1000L);
Why you have "dd-mm-yyyy" in SimpleDateFormat and "dd-MM-yyyy" in DateFormat.format? Use this :
String date = DateFormat.format("dd-mm-yyyy", cal).toString();
If you want minutes, if you want months you have to put MM like #Jesper said :)
I should like to contribute the modern answer.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("da"));
String unixTimeStampString = "1427101853";
int dateMulti = Integer.parseInt(unixTimeStampString);
ZonedDateTime dateTime = Instant.ofEpochSecond(dateMulti)
.atZone(ZoneId.of("Africa/Conakry"));
String formattedDate = dateTime.format(dateFormatter);
System.out.println(formattedDate);
The output from this snippet is:
23-03-2015
The output agrees with an online converter (link at the bottom). It tells me your timestamp equals “03/23/2015 # 9:10am (UTC)” (it also agrees with the date you asked the question). Please substitute your time zone if it didn’t happen to be Africa/Conakry.
The date-time classes that you were using — SimpleDateFormat, Date and Calendar — are long outdated and poorly designed, so I suggest you skip them and use java.time, the modern Java date and time API, instead. A minor one among the many advantages is it accepts seconds since the epoch directly, so you don’t need to convert to milliseconds. While this was no big deal, doing your own time conversions is a bad habit, you get clearer, more convincing and less error-prone code from leaving the conversions to the appropriate library methods.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) 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.
I wrote and ran the above snippet using the backport to make sure it would be compatible with ThreeTenABP.
Links
Timestamp Converter
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.
I was also facing the same issue when I was using SimpleDateFormat Here is a method I have made, which is working fine for me.
private String getmDate(long time1) {
java.util.Date time = new java.util.Date((long) time1 * 1000);
String date = DateFormat.format("dd-MMM-yyyy' at 'HH:mm a", time).toString();
return date + "";
}
you can change the date format as you desire.
I want to convert Long value to String or Date in this format dd/mm/YYYY.
I have this value in Long format: 1343805819061.
It is possible to convert it to Date format?
You can use below line of code to do this. Here timeInMilliSecond is long value.
String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(TimeinMilliSeccond));
Or you can use below code too also.
String longV = "1343805819061";
long millisecond = Long.parseLong(longV);
// or you already have long value of date, use this instead of milliseconds variable.
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
Reference:- DateFormat and SimpleDateFormat
P.S. Change date format according to your need.
You can use method setTime on the Date instance or the contructor Date(long);
setTime(long time)
Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
Date(long date)
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
Then use the simple date formater
see http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/text/DateFormatter.html
java.util.Date dateObj = new java.util.Date(timeStamp);
Here timeStamp is your long integer which is actually timestamp in millieseconds,
you get the java date object, now you can convert it into string by this
SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat dateformatMMDDYYYY = new SimpleDateFormat("MMddyyyy");
StringBuilder nowYYYYMMDD = new StringBuilder( dateformatYYYYMMDD.format( dateObj ) );
StringBuilder nowMMDDYYYY = new StringBuilder( dateformatMMDDYYYY.format( dateObj ) );
java.time and ThreeTenABP
I am providing the modern answer. I suggest using java.time, the modern Java date and time API, for your date work. This will work on your Android version:
// Take Catalan locale as an example for the demonstration
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("ca"));
long millisecondsSinceEpoch = 1_343_805_819_061L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
String dateString = dateTime.format(dateFormatter);
System.out.println("As formatted date: " + dateString);
Output is:
As formatted date: 01/08/2012
I recommend that you use a built-in localized date format for presentation to your user. I took Catalan date format just as an example. Formats for many languages, countries and dialects are built-in.
The SimpleDateFormat class used in most of the old answers is a notorious troublemaker of a class. The Date class also used is poorly designed too. Fortunately they are both long outdated. It’s no longer recommended to use any of those. And I just find java.time so much nicer to work with.
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.
if thre is 10 digits in long then try this
long DateInLong= 1584212400;
Date date = new Date(DateInLong*1000L);
SimpleDateFormat simpledateformate= new SimpleDateFormat("yyyy-MM-dd");
String DATE = simpledateformate.format(date);
public String getDuration(long msec) {
if (msec == 0)
return "00:00";
long sec = msec / 1000;
long min = sec / 60;
sec = sec % 60;
String minstr = min + "";
String secstr = sec + "";
if (min < 10)
minstr = "0" + min;
if (sec < 10)
secstr = "0" + sec;
return minstr + ":" + secstr;
}