I am working on an XML Parser for Android with twelve different items and I need help creating a date for each item. This is what I have so far:
TextView detailsPubdate = (TextView)findViewById(R.id.detailspubdate);
I am looking to make the date look like this: Saturday, September 3. Thank you for your help!
java.time
In March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy java.util
date-time API. Any new code should use the java.time
API*.
I am looking to make the date look like this: Saturday, September 3.
Apart from the format and the use of modern API, the most important point to consider is Locale
. The text you want to get is in English; therefore, if you do not use Locale
in your code, the output will be in the default Locale
set in the JVM in which your code will be executed. Check Always specify a Locale with a date-time formatter for custom formats to learn more about it.
Get the current date-time using a ZonedDateTime now(ZoneId)
and format it as required.
Demo:
public class Main {
public static void main(String args[]) {
// ZoneId.systemDefault() returns the default time zone of the JVM. Replace it
// with the applicable ZoneId e.g., ZoneId.of("America/Los_Angeles")
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// Default format
System.out.println(now);
// Formatted string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMMM d", Locale.ENGLISH);
String formattedString = now.format(formatter);
System.out.println(formattedString); // detailsPubdate.setText(formattedString);
}
}
Output:
2024-11-10T12:02:02.644429400Z[Europe/London]
Sunday, November 10
Note: For whatever reason, if you need an instance of java.util.Date
from this object of ZonedDateTime
, you can do so as follows:
Date.from(now.toInstant());
Learn more about the modern date-time API from Trail: Date Time.
* If you receive a java.util.Date
object, convert it to a java.time.Instant
object using Date#toInstant
, and derive other java.time
date-time objects from it.