Format Date on Server Response from REST API not working - java

I have a method that gets data from REST server. The method returns the date in this format "2017-08-14T17:45:16.24Z". i also wrote a method that formats date in the order "dd/MM/yyyy". This works perfectly but when i try to format the date from the server and set the that to an Edittext it does not work. This shows shows that my method to format the date in the server response does not work. My method to format the date is below:
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 "";
}
This method below that gets the date from the server and formats the date and sets the date to an Edit-text.
public void getProfile() {
Retrofit retrofit = RetrofitClient.getClient(authUser.getToken());
APIService mAPIService = retrofit.create(APIService.class);
mAPIService.getProfile("Bearer " + authUser.getToken()).enqueue(new Callback<Profile>() {
#Override
public void onResponse(Response<Profile> response, Retrofit retrofit) {
if(response.isSuccess()) {
try {
String loginSuccess = response.body().getSuccess();
if (loginSuccess.equals("true")) {
id_name.setText(response.body().getData().getName());
id_email.setText(response.body().getData().getEmail());
phone_input_layout.setText(response.body().getData().getPhoneNumber());
id_gender.setText(response.body().getData().getGender());
String dateOfBirth = response.body().getData().getDateOfBirth();
id_date_of_birth.setText(formatDate(dateOfBirth));
//updateLabel(dateOfBirth);
id_residential_address.setText(response.body().getData().getResidentialAddress());
if (response.body().getData().getEmploymentStatus().equals("Student")) {
id_nss_number.setVisibility(View.VISIBLE);
maximum_layout.setVisibility(View.INVISIBLE);
extended_layout.setVisibility(View.INVISIBLE);
} else if (response.body().getData().getEmploymentStatus().equals("Employed")) {
maximum_layout.setVisibility(View.VISIBLE);
extended_layout.setVisibility(View.INVISIBLE);
id_nss_number.setVisibility(View.INVISIBLE);
id_type.setText(response.body().getData().getIdType());
id_number.setText(response.body().getData().getIdNumber());
id_expiry_date.setText(response.body().getData().getIdExpiryDate());
}
} else {
String message = response.body().getMessage();
Log.e("getProfileError", message);
Toast.makeText(UserProfileActivity.this, message, Toast.LENGTH_LONG).show();
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Some fields are empty", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
public void onFailure(Throwable throwable) {
Log.e("getProfileError", throwable.getMessage());
Toast.makeText(UserProfileActivity.this, "Unable to Login, Please Try Again", Toast.LENGTH_LONG).show();
}
});
}
this is the exception i get from the date format
I/dateError:: Unparseable date: "1988-11-09T00:00:00Z"

Your desired format is
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
The last Z stands for "zero hour offset" also known as "Zulu time" (UTC).
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
With this UTC timezone, converted hour will be 20H.
If you don't add timezone you will have your expected hour 17H.

this is the error i get from my formatDate I/dateError:: Unparseable date: "1988-11-09T00:00:00Z" (at offset 19)
That date-time string has got no decimals on the second (and no decimal point). Offset 19 is where the Z is, and where the decimal point is in your format pattern string. This causes your exception.
java.time, the modern Java date and time API, will solve your problem easily:
private static final DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd/MM/yyyy");
private static String formatDate(String dateString) {
return Instant.parse(dateString)
.atZone(ZoneId.of("Australia/Queensland"))
.format(dateFormatter);
}
This will work with and without decimals on the seconds:
System.out.println(formatDate("2017-08-14T17:45:16.24Z"));
System.out.println(formatDate("1988-11-09T00:00:00Z"));
This prints
15/08/2017
09/11/1988
You may be surprised that the first line says the 15th of the month when the day-of-month in the string is 14. This is because when it is 17:45 in UTC, it is already the next day in Australia. I suppose you want the day in your user’s time zone. Therefore please substitute your desired time zone if it didn’t happen to be Australia/Queensland. If you do want the date in UTC, use this line instead of the atZone call:
.atOffset(ZoneOffset.UTC)
This will make sure you get the same date as in the string.
As a detail, the above code also parses your 0.24 seconds correctly. SimpleDateFormat understood 24 as 24 milliseconds, so you got 0.024 seconds instead, a slight inaccuracy. Another detail, I declared your method static, it’s not necessary, but we might as well.
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.
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.

Related

How to parse "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" date format to simple in Android? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 4 years ago.
How do I can parse this date 2018-01-09T11:11:02.0+03:00 to dd.MM.yyyy hh:mm format in Android?
And what does T between 09 and 11 mean?
Thanks.
I don't know how the back-end developer got this format.
I am using Java.
You can do this with SimpleDateFormat.
Here is a tested example in Java:
String dateString = "2018-01-09T11:11:02.0+03:00";
String inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
String outPattern = "dd.MM.yyyy hh:mm";
SimpleDateFormat inFormat = new SimpleDateFormat(inPattern, Locale.getDefault());
SimpleDateFormat outFormat = new SimpleDateFormat(outPattern, Locale.getDefault());
try {
Date inDate = inFormat.parse(dateString);
String outDate = outFormat.format(inDate);
Log.e("TEST", outDate);
} catch (ParseException e) {
e.printStackTrace();
}
Here is a tested example in Kotlin:
val dateString = "2018-01-09T11:11:02.0+03:00"
val inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
val outPattern = "dd.MM.yyyy hh:mm"
val inFormat = SimpleDateFormat(inPattern, Locale.getDefault())
val outFormat = SimpleDateFormat(outPattern, Locale.getDefault())
val inDate = inFormat.parse(dateString)
val outDate = outFormat.format(inDate)
Log.e("TEST", outDate)
If you are using java, you can use SimpeDateFormat with patterns:
String date = "2018-01-09T11:11:02.0+03:00";
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
SimpleDateFormat output = new SimpleDateFormat("dd.MM.yyyy hh:mm");
Date d = null;
try {
d = dateformat.parse(date /*your date as String*/);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = output.format(d);
Log.d("Date format", "output date :" + formattedDate);
The output is :
D/Date format: output date :09.01.2018 09:11
EDIT : Thanks to #OleV.V., for API > 26, or using ThreeTenABP we can use
DateTimeFormatter, we can do something like that
String date = "2018-01-09T11:11:02.0+03:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm");
LocalDate parsedDate = LocalDate.parse(date, formatter);
String formattedDate = formatterOut.format(parsedDate);
Log.d("Date format", "output date :" + formattedDate);
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String backendDateTimeString = "2018-01-09T11:11:02.0+03:00";
OffsetDateTime dateTime = OffsetDateTime.parse(backendDateTimeString);
String presentationDateTimeString = dateTime.format(desiredFormatter);
System.out.println(presentationDateTimeString);
This prints:
09.01.2018 11:11
Please note: I am using uppercase HH in the format pattern string. This indicates hour of day from 00 through 23. In the question you used lowercase hh, which in a format pattern string means hour with AM or PM from 01 through 12, so 00:33 would come out as 12:33 and 15:47 as 03:47. I didn’t think you intended this.
The format that your backend developer got, 2018-01-09T11:11:02.0+03:00, is ISO 8601. It’s widespread, and it’s the international standard, so it’s good that s/he got that. The funny T in the middle indicates the start of the time part to separate it from the date part. The one-arg OffsetDateTime.parse method parses ISO 8601, which is why we didn’t need any formatter for parsing. OffsetDateTime and DateTimeFormatter are classes from java.time, the modern Java date and time API.
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 (API level 26 and up) 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 (my code was tested with these imports).
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.
Wikipedia article: ISO 8601

Android - Displaying month name for different date formats

I have an app that displays dates and times in a localized format for different areas, that is - it shows a user dates and times based on his preference. But my issue is that it always displays numbers, ie yyyy.mm.dd, or mm/dd/yyy, or dd,mm,yyyy. What I would like to have is this: show date so that the day is a number, year is a number, but the month is displayed as a string, ie. Jan / Xin / Gen / Jān / Yan... or 01 Jan 2018 / Jan 01 2018 / 2018 Jan 01, and so on, but still keep the current local formatting. I know that I could do that if I hardcode it like MMM, but I want it to change, depending on the localized format.
So basically this is my question: how can I display localized time, from a value I get from the server (yyyy-MM-dd HH: mm: ss), with month displayed as a three letter word, no matter what locale it uses?
I know this question sounds familiar, but so far I have tried a lot of answers, both on stack overflow, and other sources, but without any success. Some of the things I have tried include: 1 / 2 / 3 / 4 / 5 / 6 ... but I couldn't make it work in my example.
My Adapter:
public void onBindViewHolder(RestaurantsAdapter.RestaurantsViewHolder holder, int position) {
// getting restaurant data for the row
Restaurant restaurant = restaurant Items.get(position);
holder.userName.setText(restaurant .getUserName());
holder.date.setText(convertDate(restaurant .getDateTime())); //string dobiti u formatu, pretvoriti ga u localized i podijeliti na dva dijela
holder.time.setText(convertTime(restaurant .getDateTime()));
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(0)
.toUpperCase()
.endConfig()
.roundRect(10);
ColorGenerator generator = ColorGenerator.MATERIAL;
int color = generator.getColor(restaurant.getUserId());
TextDrawable textDrawable = builder.build(restaurant Items.get(position).getUserName().substring(0, 1), color);
holder.thumbNail.setImageDrawable(textDrawable);
Picasso.with(context)
.load(AppConfig.URL_PROFILE_PHOTO + restaurant.getThumbnailUrl())
.placeholder(textDrawable)
.error(textDrawable)
.transform(new RoundedTransform(12, 0))
.fit()
.centerCrop()
.into(holder.thumbNail);
}
private String convertDate(String time) {
final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());
java.util.Date date = null;
try {
date = dateFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatConverted.format(date);
}
private String convertTime(String time) {
final DateFormat shortTimeFormat = android.text.format.DateFormat.getTimeFormat(context.getApplicationContext());
SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat timeFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortTimeFormat).toPattern(), Locale.getDefault());
java.util.Date date = null;
try {
date = timeFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return timeFormatConverted.format(date);
}
UPDATE:
I tried adding this to my solution:
private String convertDate(String time) {
final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
Calendar Now = Calendar.getInstance();
Now.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());
dateFormatConverted.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
java.util.Date date = null;
try {
date = dateFormatReceived.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatConverted.format(date);
}
I think the following method will give you the date-time formatter you want.
public static DateTimeFormatter getLocalizedDateFormatter(Locale requestedLocale) {
String formatPatternString = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null,
Chronology.ofLocale(requestedLocale), requestedLocale);
// if not already showing month name, modify so it shows abbreviated month name
if (! formatPatternString.contains("MMM")) {
formatPatternString = formatPatternString.replaceAll("M+", "MMM");
}
return DateTimeFormatter.ofPattern(formatPatternString, requestedLocale);
}
Test:
Locale[] locales = { Locale.US, Locale.FRANCE, Locale.GERMANY,
Locale.forLanguageTag("da-DK"), Locale.forLanguageTag("sr-BA") };
LocalDate today = LocalDate.now(ZoneId.of("Europe/Sarajevo"));
for (Locale currentLocale : locales) {
DateTimeFormatter ldf = getLocalizedDateFormatter(currentLocale);
System.out.format(currentLocale, "%-33S%s%n",
currentLocale.getDisplayName(), today.format(ldf));
}
Output:
ENGLISH (UNITED STATES) Dec/24/17
FRENCH (FRANCE) 24/déc./17
GERMAN (GERMANY) 24.Dez.17
DANSK (DANMARK) 24-dec.-17
SERBIAN (BOSNIA AND HERZEGOVINA) 17-дец-24
JSR-310 also known as java.time
You tried to use the long outdated and notoriously troublesome classes DateFormat and SimpleDateFormat. Instead I recommend you make it a habit to use JSR-310, the modern Java date and time API. So I do that in the method above.
I don’t think it was part of the question, but for the sake of completeness, parse the date-time string as follows. The formatter you get from my getLocalizedDateFormatter can be used for formatting a LocalDateTime and many other date-time types in addition to LocalDate.
LocalDateTime ldt = LocalDateTime.parse("2017-12-24 22:51:34",
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
String formattedDate = ldt.format(getLocalizedDateFormatter(Locale.UK));
Question: Can I use JSR-310 on Android?
Yes you can. It just requires at least Java 6.
In Java 8 and later 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).
On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP.
In the latter two cases, make sure to add the appropriate edition of the backport library to your project, use the links below, and to import the classes I use from org.threeten.bp and org.threeten.bp.format.
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, where the modern date and time API was first described.
Please try to use
getDisplayName(...) method
In order to get more information you had better go through this documentation
Editted
More sufficiently you can try this way:
int monthOfYear = Calendar.JULY; // 6
String monthName = new
DateFormatSymbols(Locale.getDefault()).getShortMonths()[monthOfYear];

How to compare two dates along with time in java

I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I want to compare the above two dates along with time.
How should I compare in Java.
Thanks
Since Date implements Comparable<Date>, it is as easy as:
date1.compareTo(date2);
As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).
Note that Date has also .after() and .before() methods which will return booleans instead.
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);
if (afterSix) {
System.out.println("Go home, it's after 6 PM!");
}
else {
System.out.println("Hello!");
}
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
Question: For Android development 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

Android parsing String to Date time with SimpleDateFormat

I have the String 11/08/2013 08:48:10
and i use SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
and when im parsing it throws an exception : unparseable date
what's wrong with it ?
String result = han.ExecuteUrl("http://"+han.IP+":8015/api/Values/GetLastChange");
Log.d("Dal","result date time "+result); #result is 11/08/2013 08:48:10
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(result);
}
catch (ParseException e)
{
e.printStackTrace();
}
Its working try parse your date like this..
String dtStart = "11/08/2013 08:48:10";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
date = format.parse(dtStart);
System.out.println("Date ->" + date);
} catch (ParseException e) {
e.printStackTrace();
}
Working code is here.
You can use below code to convert from String to Date
String myStrDate = "11/08/2013 08:48:10";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date date = format.parse(myStrDate);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For reverse, it means, to convert from Date to String
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date date = new Date();
String datetime = myFormat.format(date);
System.out.println("Current Date Time in give format: " + datetime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For more reference, regarding Date and Time formatting. Visit developer site
java.time and ThreeTenABP
It’s not the answer that you asked for, but it should be the answer that other readers want in 2020 and onward.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
String result = "11/08/2013 08:48:10";
LocalDateTime dateTime = LocalDateTime.parse(result, formatter);
System.out.println("Parsed date and time: " + dateTime);
Output from this snippet is:
Parsed date and time: 2013-11-08T08:48:10
The Date class that you used is poorly designed and long outdated, so don’t use that anymore. Instead I am using java.time, the modern Java date and time API. If you need a Date for a legacy API that you cannot afford to upgrade just now, the conversion is:
Instant i = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(i);
System.out.println("Converted to old-fashioned Date: " + oldfashionedDate);
Converted to old-fashioned Date: Fri Nov 08 08:48:10 CET 2013
What went wrong in your code?
what's wrong with it ?
The only thing wrong with your code is you’re using the notoriously troublesome SimpleDateFOrmat and the poorly designed Date class. Which wasn’t wrong when you asked the question in 2013. java.time didn’t come out until 4 months later.
Your code is running fine. One may speculate that a leading space or the like in your string has prevented parsing. If this was the problem, try parsing result.trim() rather than just result since trim() returns a string with the leading and trailing whitespace removed.
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. Only in this case the conversion to Date is a little simpler: Date.from(i).
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.

How to get the weekday of a Date?

I want to get the day of week from the Java Date object when I have an array of Date in String with me.
SimpleDateFormat sourceDateformat = new SimpleDateFormat("yyyy-MM-dd");
public String[] temp_date;
public Int[] day = new Int[5];
Date[] d1= new Date[5];
Calendar[] cal= new Calendar[5]
try {
d1[i]= sourceDateformat.parse(temp_date[i].toString());
cal[i].setTime(d1[i]); // its not compiling this line..showing error on this line
day[i]= cal[i].get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e) {
e.printStackTrace();
}
Does anyone know the answer to this?
You can get the day-integer like that:
Calendar c = Calendar.getInstance();
c.setTime(yourdate); // yourdate is an object of type Date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // this will for example return 3 for tuesday
If you need the output to be "Tue" rather than 3, instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Taken from here: How to determine day of week by passing specific date?
// kotlin
val calendar = Calendar.getInstance()
val dateInfo = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.time)
data.text = dateInfo
java.time
You can do it using DateTimeFormatter.ofPattern("EEEE"):
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).format(dtfOutput);
}
}
Output:
Friday
Alternatively, you can get it using LocalDate#getDayOfWeek:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}
}
Output:
Friday
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.
This is one of the many things that have become a lot easier with the advent of java.time, the modern Java date and time API.
String tempDate = "2020-03-29";
LocalDate date = LocalDate.parse(tempDate);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Output:
SUNDAY
Of course we now have got an enum for the days of the week. There’s no longer any reason to fiddle with integers and having to remember on what day of week they begin and whether the days are numbered from 0 or 1.
I am expoiting the fact that your expected input format (yyyy-MM-dd in your code) is ISO 8601, the default for java.time, so we don’t need to specify any formatter explicitly.
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
In Kotlin, just do this:
val yourDateStr = "2021-01-01"
val df = DateFormat.parse(yourDateStr)
val weedDay = df.getWeekDay(yourTimeZone)
the below code works, depending on what number you enter in the DAY_OF_WEEK, that returns the specific weekday, in this example it always returns a future date and day will always be Tuesday.
DAY_OF_WEEK
public static String getTodaysDateAndTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5);
cal.add(Calendar.DAY_OF_WEEK, 2);
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String futureDate = dateformat.format(date);
System.out.println(futureDate);
return futureDate;
}

Categories

Resources