Date string from GregorianCalendar based on locale - java

I am creating an Android application. I have a GregorianCalendar variable. I want to get the date from this variable as MM-dd-yyyy if the locale is US or dd-MM-yyyy if the locale is EU and so on. I don't want to hard code each locale string, I want to make it depend on the phone's locale.
The problem is that after looking through tens of similar questions, I still couldn't get this to work. I am guessing it's two or three lines of code, perhaps using SimpleDateFormat or GregorianCalendar.get() or getDisplayName().
Thanks for the help.

try this
GregorianCalendar gc = ...
String str = DateFormat.getDateInstance(DateFormat.SHORT).format(gc.getTime());
BTW default date format (SHORT) for US is dd/MM/yy eg 30/05/13

Did you try this
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourcalender.getTime());
with yourcalender is GregorianCalendar variable

Better yet why not use the user's own preferred date format? Locale.getLocale() returns the user's preferred locale, you can use this to format all your localised values (dates, times, currency etc) and know that you're giving the user a format that they chose.

Related

Java printf with date and month

System.out.printf("Time: %d-%d %02d:%02d" +
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE);
That is the code a friend showed me, but how do I get the date to appear in a Format like November 1?
This is how to do it:
DateFormat dateFormat = new SimpleDateFormat( "MMMMM d" );
Calendar calendar = new GregorianCalendar(); // The date you want to format
Date dateToFormat = calendar.getTime();
String formattedDate = dateFormat.format( dateToFormat );
System.out.println( formattedDate );
Date d = new Date();
System.out.printf("%s %tB %<td", "Today", d);
// output :
// Today november 01
%tB for Locale-specific full month name, e.g. "January", "February".
%<td d for Day of month, formatted as two digits with leading zeros as necessary, < for reuse the last parameter.
The DateFormat answer is the way to do this. The printf answer is also good although does not provide locale-specific formats (it provides language-specific names but does not use e.g. the day/month/year ordering that the current locale uses).
You asked in a comment:
Can I do it with the calendar.get(Calendar.MONTH) etc method? Or do I have to use date format?
You don't have to use the other methods here, but if you want to use the Calender fields, it is up to you to convert the numeric values they provide to strings like "Tuesday" or "November". For that you can use the built in DateFormatSymbols, which provides internationalized strings from numbers for dates, in the form of String arrays, which you can use the Calendar fields to index in to. See How can I convert an Integer to localized month name in Java? for example.
Note you can use DateFormat.getDateInstance() to retrieve a pre-made format for the current locale (see the rest of those docs, there are also methods for getting pre-made time-only or date+time formats).
Basically you have the following options:
DateFormat (SimpleDateFormat for custom formats)
Locale-specific format (e.g. day/month/year ordering): Yes
Language-specific names (e.g. English "November" vs. Spanish "Noviembre"): Yes
Does the work for you: Yes. This is the best way and will provide a format that the user is used to working with, with no logic needed on your end.
printf date fields
Locale-specific format: No
Language-specific names: Yes
Does the work for you: Partly (up to you to determine field ordering)
Calendar fields with DateFormatSymbols
Locale-specific format: No
Language-specific names: Yes
Does the work for you: No
Calendar fields with your own string conversions (like a big switch statement):
Locale-specific format: No
Language-specific names: No
Does the work for you: No
Another advantage of DateFormat-based formats vs printf date fields is you can still define your own field ordering and formats with the SimpleDateFormat (just like printf) but you can stick to the DateFormat interface which makes it easier to pass around and combine with stock date formats like DateFormat.getDateInstance(DateFormat.MEDIUM).
Check out the documentation for DateFormat for info on the things you can do with it. Check out the documentation for SimpleDateFormat for info on creating custom date formats. Check out this nice example of date formats (archive) for some example output if you want instant gratification.
There's a direct way how to do it using printf, but it's a pain, too:
String.printf("Time: %1$td-%1$tm %1$tH:%1$tM", new Date());
One problem with it is that it uses 4 formatting strings with the same object, so it needs the 1$ prefix to always access the first argument. The other is that I can never remember what letter means what (but maybe that's just me).
Speed could actually be another problem, if you care.
This is documented in the underlying class Formatter.
My preffered way would be something like
myFormatter.format("Time: [d-m HH:MM]", new Date())
where the braces would save us from repeating $1 and make clear where the argument ends.

How to getDate with yyyy-MM-dd format

How can I get the current date of the system with this format yyyy-MM-dd
I want this
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String strDate = formatDate.format(now);
return strDate;
but returning a Date instead of a String.
Any help is greatly appreciated.
UPDATE: If that's the case, can I parse my String to Date?
How can i get the current date of the system with this format yyyy-MM-dd but returns Date instead of String.
You can't. There's no such thing as "a Date with a format" any more than there's the concept of "an int with a format". A Date value is just a point in time, with no associated text format, calendar system or time zone.
Using new Date() will get you a Date object representing the current instant in time, and nothing else. How you use that is up to you - but if you return it from a method then there is no associated date (as the date will vary by time zone), no format etc - it's up to the calling code to use it appropriately.
You might want to consider using Joda Time which at least has a LocalDate type - although you still need to consider which time zone you want to use when you think about "the current date". (And there's still no formatting information associated with the value.)
EDIT: To answer your update, you can just use SimpleDateFormat to parse - but it's not clear where your string has come from to start with. This sounds like the opposite requirement from the rest of your question.
since you cant change Date format build your own CustomDate, it is just a representation of time.
on the method which recieves the date as a string
use another simpledateformatter
and convert the string into date by using
simpledateformatter.parse(strDate);
You can use this .!!
String formatDate = new SimpleDateFormat("yyyy-MM-dd").format( yourDate);

can we get the pattern of the given date object

How to get the pattern of the given date object
I am getting one Date object as a parameter in my method and I want to know the pattern of the date to convert it into user selected timezone.
You've misunderstood what a Date means. It's just a number of milliseconds since the Unix epoch. It has no concept of time zone, calendar or text format. If it helps, think of it as being a bit like int - an int isn't in hex, decimal or binary - it's just a number within a certain range. If you parse "1a" as hex, that gives an indistinguishable result from parsing "26" as decimal. The same goes for Date.
Of course, this was already explained in comments to some extent, but your reply of:
ok, but while i getting the date object which already set a format i want to know that format.
... suggests you didn't really understood it. The concept of "which already set a format" makes no sense in the context of a Date.
If you need a particular format to be applied, you should pass the DateFormat along as well as the Date.
You can't from the date object itself however (depending on your exact requirements) you could use
DateFormat.getDateTimeInstance()
Which will return to you the default style and format for the locale however like I said that's dependant on your requirement...
The alternative is change your method signature to accept the format as well.
You should create DateFormat. Date knows nothing about TimeZone.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
// Set TimeZone
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(formatter.format(date));
// Change timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(formatter.format(date));

Java Date format

I have a spring web application that runs in Tomcat. I must set the date and number format for my application to a special format.
Can I set the format in any descriptor to the special in my application or I can set the all system format only?
I want to use this pattern: yyyy.mm.dd.
This code is wrong because it's not a standard locale pattern:
String currentDate = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date());
But I don't want type the pattern everywhere in the application, I want set the pattern once.
I want if I type this code:
String currentDate = SimpleDateFormat.getDateInstance(DateFormat.SHORT).format(new Date());
The result is: 2010.08.04.
Is it possible?
java.util.Date objects do not have a format by themselves (they only represent the date and time value, just like integers only represent a number value and don't know anything about formatting numbers).
There is no system-wide default date format setting. When you print a Date object by (implicitly or explicitly) calling toString() on it, it will be printed with a fixed, default format that you can't change:
System.out.println(new Date());
// Example output: Wed Aug 04 09:46:57 CEST 2010
If you want to show a date with a specific format, use a java.text.DateFormat object to format it. For example:
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(df.format(new Date()));
// Example output: 04-08-2010 09:48:47
You can absolutely format a date any way you want, no matter if you use Spring or not. First though make sure that you really need a "special formatting", not just a format that is default for a certain locale (like deCH or svSE or enGB) because if you just want to convert a date to your countries native date formatting you can simply use
String currentDate = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.UK).format(new Date());
And if you really want a custom formatting, you can do like this
String currentDateMyFormat = new SimpleDateFormat("dd:MMM:yy HH.mm").format(new Date());
Of course you can reverse the process (from String to Date) by replacing format with parse.
Hope this answers your question because just like Xu before me, I am not sure I understood your question completely ;)
Since you're talking about doing something application-wide, let me remind you to be cautious with any java.text.Format subclass (including DateFormat, SimpleDateFormat, etc.). As noted in the Javadoc, Formats are generally not thread-safe. I know from personal experience that DateFormats are not.
Therefore, if you're considering setting something up for use across your application, I recommend only defining the format String and sharing it around the application. Instances of a Format class are best-defined in a thread-safe manner, such as on the stack of a method call.

Date display in different locales in Java?

In java how do I display dates in different locales (for e.g. Russian).
Something like:
Locale locale = new Locale("ru","RU");
DateFormat full = DateFormat.getDateInstance(DateFormat.LONG, locale);
out.println(full.format(new Date()));
Should do the trick. However, there was a problem of Russian Date formatting in jdk1.5
The deal with Russian language is that month names have different suffix when they are presented stand-alone (i.e. in a list or something) and yet another one when they are part of a formatted date. So, even though March is "Март" in Russian, correctly formatted today's date would be: "7 Марта 2007 г."
Let's see how JDK formats today's date: 7 Март 2007 г. Clearly wrong.
Use SimpleDateFormat constructor which takes locale. You need to first check if JDK supports the locale you are looking for, if not then you need to implement that.
Use the java.text.DateFormat class, you can construct that's configured to a specific Locale.
DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM, theLocaleYouWant);
String text = format.format(new Date());
System.out.println(text);
The DateFormat class can help you. As explained in the Javadoc:
To format a date for a different
Locale, specify it in the call to
getDateInstance().
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
So you just need to adapt this code by using the adequate Locale.
Use a java.util.Calendar with an appropriate time zone and locale.

Categories

Resources