0

I am using TextView to set date and time with day name, but time is showing in 24hours and I want to set it in 12hours format. can any one help me what should I change in this format.

textDateTime.setText(new SimpleDateFormat("EEEE, dd MMMM yyyy HH:mm a", Locale.getDefault()).format(new Date()));
Asad
  • 1
  • 2
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. May 18 '21 at 18:21

2 Answers2

5

It's about the format you put in SimpleDateFormat, as you are using HH (24-hour). Try hh (12-hour format). See related answer or the doc.

2

tl;dr

Use modern java.time classes.

Rather than hard-code a format, automatically localize.

LocalTime
.now()
.format(
    DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT )
)

See this code run live at IdeOne.com.

5:08 PM

Avoid legacy classes

Never use the terrible Date and SimpleDateFormat classes. These were years ago supplanted by the modern java.time classes defined in JSR 310.

java.time

You appear to want the current time as seen in a particular time zone. Time zone is crucial. For any given moment, the time-of-day (and the date) vary around the globe by time zone.

ZoneId z = ZoneId.systemDefault() ;  // Or ZoneId.of( "America/Edmonton" )
LocalTime now = LocalTime.now( z ) ;

Let java.time automatically localize for you.

Locale locale = Locale.CANADA_FRENCH ;  // Or Locale.US etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;
String output = now.format( f ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154