Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date without year

Tags:

java

date

How can create text representation of some date, that takes locale into account and contains only day and month (no year)?

Following code gives me something like 23/09/2010

DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(date); 

I want to get 23/09

like image 683
fhucho Avatar asked Sep 24 '10 20:09

fhucho


People also ask

What happens when you enter a date in a cell without including the year?

Short answer: There's no way to have a date without a year, it's simply a required part of a date. Just like the second is a required part of the time of day - if you enter, say, "1:15", the actual value will be "01:15:00" (or something like that, depending on your regional settings).

How do I format date only month and year?

Display only option If you only want to display a date with the year and month, you can simply apply the custom number format "yyyymm" to the date(s). This will cause Excel to display the year and month together, but will not change the underlying date.


2 Answers

This will work for Android, in case someone needs it:

int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR; String monthAndDayText = DateUtils.formatDateTime(context, date, flags); 
like image 70
unify Avatar answered Sep 23 '22 09:09

unify


You could use regex to trim off all y's and any non-alphabetic characters before and after, if any. Here's a kickoff example:

public static void main(String[] args) throws Exception {     for (Locale locale : Locale.getAvailableLocales()) {         DateFormat df = getShortDateInstanceWithoutYears(locale);         System.out.println(locale + ": " + df.format(new Date()));           } }  public static DateFormat getShortDateInstanceWithoutYears(Locale locale) {     SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);     sdf.applyPattern(sdf.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", ""));     return sdf; } 

You see that this snippet tests it for all locales as well. It looks to work fine for all locales here.

like image 42
BalusC Avatar answered Sep 20 '22 09:09

BalusC