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!
If you are looking for todays date, you can do this by using the Date
object.
Date today = new Date();//this creates a date representing this instance in time.
Then pass the date to the SimpleDateFormat.format(Date)
method.
// "EEEE, MMMM, d" is the pattern to use to get your desired formatted date.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM, d");
String formattedDate = sdf.format(today);
Finally, you can set this String
into your TextView
detailsPubdate.setText(formattedDate);
Here is the documentation for SimpleDateFormat
. The documentation shows the various patterns available to format Date
objects.
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
Online Demo
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With