Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I utilize SimpleDateFormat with Calendar?

I've got GregorianCalendar instances and need to use SimpleDateFormat (or maybe something that can be used with calendar but that provides required #fromat() feature) to get needed output. Please, suggest work arounds as good as permanent solutions.

like image 856
Denys S. Avatar asked Apr 11 '11 13:04

Denys S.


People also ask

How do you use SimpleDateFormat?

Creating SimpleDateFormat instance String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); In the example above the String pattern is the pattern which will be used to format a date and the output will be generated in that pattern as “MM-dd-yyyy”.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

How do you format a date in a calendar?

Day/Month/Year – DD/MM/YYYY – Mainly used in European languages, as well as the United Nations when writing the full date format in official documents. It's also used in India, Australia, and most of Africa and Latin America. Year/Month/Day – YYYY/MM/DD – Mostly found in the Chinese language.


2 Answers

Try this:

Calendar cal = new GregorianCalendar(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); dateFormat.setTimeZone(cal.getTimeZone()); System.out.println(dateFormat.format(cal.getTime())); 
like image 65
janhink Avatar answered Oct 10 '22 20:10

janhink


eQui's answer is missing a step

Calendar cal = new GregorianCalendar(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); #---- This uses the provided calendar for the output ----- dateFormat.setCalendar(cal);  System.out.println(dateFormat.format(cal.getTime())); 
like image 40
JamesKingston Avatar answered Oct 10 '22 21:10

JamesKingston