Reputation: 14717
I am using Java 7 and I need to display the time part of a Java Date
object.
I notice that DateFormat
has the SHORT
constant according to the page and the page has the following description:
SHORT
is completely numeric, such as 12.13.52 or 3:30pm
My question is how to display only the time part (such as "3:30pm"). The following is what I have and it only shows the date part (such as 2/14/15):
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT, A_Locale_object);
SimpleDateFormat sf = (SimpleDateFormat) f;
sf.format(new Date());
Upvotes: 0
Views: 85
Reputation: 11
Use getTimeInstance
instead of getDateInstance
.
DateFormat f = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.getDefault());
Upvotes: 1
Reputation: 338584
The Question and other Answers neglect the crucial issue of time zone. If not specified, the JVM’s current default time zone is automatically applied.
Such work is easier with the Joda-Time library.
Example using Joda-Time 2.7.
Translate the java.util.Date object to a Joda-Time DateTime
object. Unlike a Date
, a DateTime
understands its assigned time zone. We want to adjust from the Date
object’s UTC zone to a desired zone such as Montréal.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
DateTime dateTime = new DateTime( yourDate, zone ) ;
Generate a String representation of this date-time value. A pair of characters passed to forStyle
control the full, long, short etc. format of the date portion and the time portion. A hyphen suppresses display of that portion.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "-S" ).withLocale( Locale.CANADA_FRENCH ) ;
String output = formatter.print( dateTime ) ;
Upvotes: 1
Reputation: 691735
If what you want to display is the time part, what ou need to call is getTimeInstance()
, and not getDateInstance()
.
This is the kind of answer that you should learn to find by yourself, simply by reading the javadoc:
Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format.
Upvotes: 3
Reputation: 11
So If you want to display the time part, what you can do is provide the format to SimpleDatFormat and your locale like below
SimpleDateFormat sf = new SimpleDateFormat("hh:mm a", your_locale);
And format it like you did
sd.format(new Date()));
If you want more stuff to be formatted, you can definitely add more like "YY.MM.dd hh:mm a"
You can read the SimpleDateFormat document for more info http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Upvotes: 1