I'm trying to return the name of the month as a String, for instance "May", "September", "November".
I tried:
int month = c.get(Calendar.MONTH);
However, this returns integers (5, 9, 11, respectively). How can I get the month name?
Use this :
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());
Month name will contain the full month name,,if you want short month name use
this
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
String month_name = month_date.format(cal.getTime());
For getting month in string variable use the code below
For example the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September
String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())
Use getDisplayName.
For earlier API's use String.format(Locale.US,"%tB",c);
"MMMM" is definitely NOT the right solution (even if it works for many languages), use "LLLL" pattern with SimpleDateFormat
The support for 'L' as ICU-compatible extension for stand-alone month names was added to Android platform on Jun. 2010.
Even if in English there is no difference between the encoding by 'MMMM' and 'LLLL', your should think about other languages, too.
E.g. this is what you get, if you use Calendar.getDisplayName or the "MMMM" pattern for January with the Russian Locale:
января (which is correct for a complete date string: "10 января, 2014")
but in case of a stand-alone month name you would expect:
январь
The right solution is:
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
If you are interested in where all the translations come from - here is the reference to gregorian calendar translations (other calendars linked on top of the page).
As simple as this
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Calendar.LONG is to get the full name of the month and Calendar.SHORT gives the name in short.
For eg: Calendar.LONG will return January
Calendar.SHORT will return Jan
I keep this answer which is useful for other cases, but #trutheality answer seems to be the most simple and direct way.
You can use DateFormatSymbols
DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example
The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech
private String getMonthName(Calendar calendar, boolean short) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
if (short) {
flags |= DateUtils.FORMAT_ABBREV_MONTH;
}
return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}
Tested on API 15-25
Output for May is Май but not Мая
Russian.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
new Locale( "ru" , "RU" )
)
май
English in the United States.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.US
)
May
See this code run live at IdeOne.com.
ThreeTenABP and java.time
Here’s the modern answer. When this question was asked in 2011, Calendar and GregorianCalendar were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.
Depending on your exact needs and situation there are two options:
Use Month and its getDisplayName method.
Use a DateTimeFormatter.
Use Month
Locale desiredLanguage = Locale.ENGLISH;
Month m = Month.MAY;
String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
System.out.println(monthName);
Output from this snippet is:
May
In a few languages it will make a difference whether you use TextStyle.FULL or TextStyle.FULL_STANDALONE. You will have to see, maybe check with your users, which of the two fits into your context.
Use a DateTimeFormatter
If you’ve got a date with or without time of day, I find a DateTimeFormatter more practical. For example:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);
ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
String monthName = dateTime.format(monthFormatter);
I am showing the use of a ZonedDateTime, the closest replacement for the old Calendar class. The above code will work for a LocalDate, a LocalDateTime, MonthDay, OffsetDateTime and a YearMonth too.
What if you got a Calendar from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime and proceed as above:
Calendar c = getCalendarFromLegacyApi();
ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);
The rest is the same as before.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I would recommend to use Calendar object and Locale, because month names are different for different languages:
// index can be in range 0 - 11
private String getMonthName(final int index, final Locale locale, final boolean shortName)
{
String format = "%tB";
if (shortName)
format = "%tb";
Calendar calendar = Calendar.getInstance(locale);
calendar.set(Calendar.MONTH, index);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return String.format(locale, format, calendar);
}
Example for full month name:
System.out.println(getMonthName(0, Locale.US, false));
Result: January
Example for short month name:
System.out.println(getMonthName(0, Locale.US, true));
Result: Jan
A sample way to get the date and time in
this format "2018 Nov 01 16:18:22" use this
DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Date date = new Date();
dateFormat.format(date);
Getting a standalone month name is surprisingly difficult to perform "right" in Java. (At least as of this writing. I'm currently using Java 8).
The problem is that in some languages, including Russian and Czech, the standalone version of the month name is different from the "formatting" version. Also, it appears that no single Java API will just give you the "best" string. The majority of answers posted here so far only offer the formatting version. Pasted below is a working solution for getting the standalone version of a single month name, or getting an array with all of them.
I hope this saves someone else some time!
/**
* getStandaloneMonthName, This returns a standalone month name for the specified month, in the
* specified locale. In some languages, including Russian and Czech, the standalone version of
* the month name is different from the version of the month name you would use as part of a
* full date. (Different from the formatting version).
*
* This tries to get the standalone version first. If no mapping is found for a standalone
* version (Presumably because the supplied language has no standalone version), then this will
* return the formatting version of the month name.
*/
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
// Attempt to get the standalone version of the month name.
String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
String monthNumber = "" + month.getValue();
// If no mapping was found, then get the formatting version of the month name.
if (monthName.equals(monthNumber)) {
DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
monthName = dateSymbols.getMonths()[month.getValue()];
}
// If needed, capitalize the month name.
if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
}
return monthName;
}
/**
* getStandaloneMonthNames, This returns an array with the standalone version of the full month
* names.
*/
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
Month[] monthEnums = Month.values();
ArrayList<String> monthNamesArrayList = new ArrayList<>();
for (Month monthEnum : monthEnums) {
monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
}
// Convert the arraylist to a string array, and return the array.
String[] monthNames = monthNamesArrayList.toArray(new String[]{});
return monthNames;
}
It will provide current date and month:
fun getDateTime(): String?
{
val dateFormat: DateFormat = SimpleDateFormat("dd MMMM")
val date = Date()
return dateFormat.format(date)
}
Related
This question already has answers here:
How does Java "week year" really work?
(2 answers)
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 1 year ago.
I am trying to format the date using the below code.
2021-01-02 returns JANUARY 2020 in one device and JANUARY 2021 on another device. Why is it so?
formatDate(transactionItem.dateLabel, "yyyy-MM-dd", "MMMM YYYY")?.toUpperCase()
public static String formatDate(String inputDate, String inputFormat, String outputFormat) {
try {
Locale appLocale = new Locale(LocaleHelper.getDefaultLanguage());
DateFormat originalFormat = new SimpleDateFormat(inputFormat, appLocale);
DateFormat targetFormat = new SimpleDateFormat(outputFormat);
Date dateObject = originalFormat.parse(inputDate);
String formattedDate = targetFormat.format(dateObject);
return formattedDate;
} catch (ParseException var9) {
return "";
} catch (Exception var10) {
return "";
}
}
There are two major and related problems in your code:
Using SimpleDateFormat without Locale: You have used new SimpleDateFormat(outputFormat) without a Locale and as such, it is error-prone. Check this answer to learn more about the problem that may occur due to lack of Locale. Since your expected output is in English, use the English type of Locale e.g. new SimpleDateFormat(outputFormat, Locale.ENGLISH).
Y is used for Week year and for SimpleDateFormat, it is Locale-sensitive i.e. it may have different values for different locales. Check this discussion to learn more about it. From your question, it looks like you mean Year and not Week year and therefore, you should use y as already specified in your inputFormat.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Learn about the modern date-time API from Trail: Date Time.
I'm trying to parse a String that represents a Date "2017-05-22" into a Date() using SimpleDateFormat(). I also need to have the date conversion in Spanish, so I'm creating a Locale with the spanish configuration. The problem is that for some reason I still get the output in English. My phones Language & Input configuration by default is English, but I've tried to change it to Spanish as well. Here is the full code:
val localeSpanish = Locale("es", "ES")
val dateFormat = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
val dateInSpanish = dateFormat.parse("2017-01-29")
And I get this in the ouput:
Wed Jan 11 00:00:00 GMT-04:00 2017
Can someone tell me what I'm doing wrong?
As stated by others, when you are outputting dateInSpanish, you are exposing a Date instance, which is calling its toString method and its implementation constructs that string based on a static array containing the words in English
//From java.util.Date
private final static String wtb[] = {
"am", "pm",
"monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday",
"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december",
"gmt", "ut", "utc", "est", "edt", "cst", "cdt",
"mst", "mdt", "pst", "pdt"
};
When you are declaring the dateFormatter, it is meant to convert a date/string as the following example:
val dateFormatter = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
println(dateFormatter.parse("2017-01-29")) // prints: Wed Jan 29 00:00:00 GMT-02:00 2017
println(dateFormatter.format(Date()) // prints: 2018-07-27 (as today :p)
I think you should use a different mask in order to obtain the formatted string.
But if you are forced to read the date in that format, you would have to declare two formatters:
val readerFormatter = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
val writerFormatter = SimpleDateFormat("d 'de' MMMM 'del' yyyy", localeSpanish)
val readDate: Date = readerFormatter.parse("2017-01-29")
val dateInSpanish: String = writerFormatter.format(readDate)
println(dateInSpanish) // prints: 29 de enero del 2017 (as today :p)
Sorry I cannot write Kotlin (yet). Can you translate form Java?
Locale localeSpanish = new Locale("es", "ES");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(localeSpanish);
LocalDate date = LocalDate.parse("2017-01-29");
String formattedDate = date.format(dateFormatter);
System.out.println("Fecha en español: " + formattedDate);
This prints:
Fecha en español: 29 de enero de 2017
Messages:
The date-time classes you were using, SimpleDateFormat and Date, are long outdated and poorly designed. SimpleDateFormat in particular has a reputation for being troublesome. And despite the name a Date represents a point in time, not a date. Instead use java.time, the modern Java date and time API.
For a date without time of day use the LocalDate class.
The format you are parsing, yyyy-MM-dd, is ISO 8601. The modern classes parse ISO 8601 as their default, that is, without any explicit formatter.
No matter if you use Date or LocalDate, they haven’t got neither a format nor a locale in them. They just hold the data in much the same way as an int holds a number without any format or locale. No matter if you have an int, a Date or a LocalDate, if you want a specific format, you can have that format only in a String.
To format a date for an audience in a locale, use a built-in date format. DateTimeFormatter.ofLocalizedDate gives you one, but you need to convert it to the desired locale.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
Simple, SimpleDateFormat.parse returns a Date object which is format agnostic. What you want to do is print the following:
val dateString = dateFormat.format(dateInSpanish)
Try using this for date representation and for local spanish time use your localSpanish val
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy MMM dd - HH:mm:ss",*your code here*);
String formattedDate = df.format(c.getTime());
The line:
val dateInSpanish = dateFormat.parse("2017-01-29")
does not format the date, it just extracts the date out of the string
The line:
val localeSpanish = Locale("es", "ES")
does not change your phone's configuration
so you have a date: dateInSpanish
and you can format it as you like and then print it
I got a Problem when converting a Date in my Android App.
My Problem is that I got two different Formats of the Date.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
DateFormat formatter_date = new SimpleDateFormat("dd.MMM.yyyy");
Date myDate = null;
try {
myDate = dateFormat.parse("28.10.2015");
} catch (ParseException e) {
e.printStackTrace();
}
formatter_date.format(myDate,"dd.MM.yyyy"))
txtDate.setText(formatter_date.format(myDate,"dd.MM.yyyy")));
I want to have the date formatted as 28.Oct.2015 on a device set to English language, as 28.Okt.2015 in German, etc. So always one dot before and after the month abbreviation. When language is set to English it returns 28.Oct.2015 as it should, however, when Language is set to German it returns 28.Okt..2015 with two dots between Okt and 2015.
Is there any solution to handling this?
I should like to challenge what you are asking for. Of course you can have it, as your own answer already shows. But do you want it?
Use the built-in localized formats
Java has localized formats for all available locales (I think it’s all, in any case it’s many). I suggest you use these rather than your own idea of what a localized date should look like. While 28.Okt.2015 is probably commonplace in Austria and other German-speaking places, English-speaking people are not used to the dots in your format, and I would suspect that some people in the world will find it more or less strange.
I suggested in a comment that you add 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. Now I am taking my own medicine:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
System.out.println(myDate.format(dateFormatter));
Output in different locales include:
German: 28.10.2015
UK English: 28 Oct 2015
French: 28 oct. 2015
It’s not what you asked for. And you may meet objections, but that will happen no matter which format you choose because many people have their own ideas about the proper formatting for their locale. It’s pretty standardized, though, so consider it.
Edit: where did the LocalDate come from?
I understood that you were converting from a string like "28.10.2015". Converting this to a LocalDate is straightforward when you know how:
DateTimeFormatter numericDateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu");
LocalDate myDate = LocalDate.parse("28.10.2015", numericDateFormatter);
Only if you got a java.util.Date from a legacy API that you cannot change or do not want to change just now, first thing convert it to the modern Instant type and do further conversions from there:
LocalDate myDate = oldfashionedJavaUtilDate.toInstant()
.atZone(ZoneId.of("Europe/Vienna"))
.toLocalDate();
Since this is a time zone sensitive operation, I recommend you specify an explicit time zone. You may use the JVM’s time zone setting by specifying ZoneId.systemDefault(), but be aware that this is fragile: the JVM setting may be changed under your feet by other parts of your program or other programs running in the same JVM.
What you asked for
The java.time edition of what you asked for is pretty similar to the code in your own answer:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM");
DateTimeFormatter yearFormatter = DateTimeFormatter.ofPattern("uuuu");
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
String dayOfMonth = myDate.format(dateFormatter);
String monthName = myDate.format(monthFormatter);
if (monthName.length() > 3) {
monthName = monthName.substring(0, 3);
}
String year = myDate.format(yearFormatter);
String formattedDate = dayOfMonth + '.' + monthName + '.' + year;
System.out.println(formattedDate);
Output in the same locales as above:
German: 28.Okt.2015
UK English: 28.Oct.2015
French: 28.oct.2015
There is a much shorter way to obtain the same, though:
String formattedDate = String.format("%1$td.%2$.3s.%1$tY",
myDate,
myDate.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()));
It’s harder to read. It took me a number of attempts to get the format string %1$td.%2$.3s.%1$tY exactly right. And it will surprise those maintaining your code if they are used to DateTimeFormatter for formatting dates (and times). So I don’t really recommend it, but the choice is yours.
With another date I got the following output in French locale:
08.jui.2018
No French-speaking person, nor anyone else for that matter, will know whether this date was in June (juin) or July (juillet). In 57 of the available locales in my JVM, all 12 months of the year begin with the same three letters. Such locales include Tibetan, Swahili, Somali, Cornish, Scottish Gaelic and Vietnamese. In these languages nobody will be able to tell any months apart. Please think twice.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
SimpleDateFormat dateFormat = new SimpleDateFormat(String pattern, Locale locale);
has another constructor with Locale change Locale.ENGLISH for date to be set in English. You can check other Locale options. I generally use Locale.getDefault() to display date in user's prefered language.
Thanks for help but this solution works best for me
DateFormat formatter_month = new SimpleDateFormat("MMMM"); //Get Whole Name of Month
DateFormat formatter_day = new SimpleDateFormat("dd."); //Get Day + Dot(2 digits)
DateFormat formatter_year = new SimpleDateFormat(".yyyy"); //Get Dot + Year(4 digits)
String str_date = formatter_day.format(date)+ //Day
formatter_month.format(date).substring(0,3)+ //Month
formatter_year.format(date); //Year
In my app, I receive dates from a webservice in the form yyyy-MM-dd (e.g. 2016-03-05) and I need to format them as [abbreviated month] [date], e.g. Mar 5. Additionally, I have a start and end date and want to show them as a date range, unless both dates are the same.
Currently I'm using DateUtils.formatDateRange(), which should take care of my requirements and provide proper localization, but I'm running into two problems:
When my end date is the day after my start date, formatDateRange()
only shows the formatted start date. For example, if start date is
2016-03-05 and end date is 2016-03-06, the method returns Mar 5 (but it should be Mar 5 - Mar 6). Why does this happen?
When the end date is in the same month, the month is not shown. For example, if start date is 2016-03-05 and end date is
2016-03-12, the method returns Mar 5 - 12. Is there a way to make it show Mar 5 - Mar 12 instead?
Here is my code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate, endDate;
try {
startDate = sdf.parse(startDateString);
endDate = sdf.parse(endDateString);
} catch (ParseException ignored) {
return null;
}
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH;
return DateUtils.formatDateRange(context, startDate.getTime(), endDate.getTime(), flags);
In the first case, the date formatter is taking your end date in the range as exclusive (as opposed to inclusive in the range). If you simply add one millisecond to the end date, you will see the ranges you expect, because now the date range includes the point in time at midnight for the end date.
In the second case, I'm afraid you are up to the current locale rules for date formatting. You pretty much have to accept what Android thinks is the best formatting, or come up with your own rules for each locale that you want to support.
tl;dr
LocalDate.parse( inputStart )
.format( DateTimeFormatter.ofPattern( "MMM d" ).withLocale( Locale.US ) )
+ " - " +
LocalDate.parse( inputStop )
.format( DateTimeFormatter.ofPattern( "MMM d" ).withLocale( Locale.US ) )
Mar 5 - Mar 6
Details
You can do this quite simply with the java.time classes rather than the troublesome old legacy date-time classes ( Date, SimpleDateFormat ) and the external library DateUtils.
Your input date strings use the standard ISO 8601 format. The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate start = LocalDate.parse( "2017-01-23" );
LocalDate stop = LocalDate.parse( "2017-02-14" );
To generate a string with just the abbreviated month name and day-of-month, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM d" );
Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
f = f.withLocale( Locale.US ) ; // Or Locale.CANADA_FRENCH, Locale.UK, Locale.ITALY, etc.
Ask the LocalDate to generate a string representing its value.
String output = start.format( f ) + " - " + stop.format( f ) ;
Jan 23 - Feb 14
MonthDay
Sounds like you may be interested in the MonthDay class if needing to work with the concept of a month and a day-of-month but without any year.
MonthDay md = MonthDay.of( 1 , 23 ) ;
Or use the Month enum to specify the month argument.
MonthDay start = MonthDay.of( Month.JANUARY , 23 ) ;
MonthDay stop = MonthDay.of( Month.FEBRUARY , 14 ) ;
To generate a string in standard ISO 8601 format, call toString.
String output = start.toString() ;
--01-23
Or use the same DateTimeFormatter seen above.
String output = start.format( f );
Jan 23
The ISO 8601 defines a format indicating a span of time using a slash character. So your same range of month-day values would be:
String output = start.toString() + "/" + stop.toString() ;
--01-23/--02-14
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
What am I doing wrong?
Thanks!
EDIT SOLUTION:
mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
if(i == 2){
dayOfTheWeek = "Mon";
} else if (i==3){
dayOfTheWeek = "Tue";
} else if (i==4){
dayOfTheWeek = "Wed";
} else if (i==5){
dayOfTheWeek = "Thu";
} else if (i==6){
dayOfTheWeek = "Fri";
} else if (i==7){
dayOfTheWeek = "Sat";
} else if (i==1){
dayOfTheWeek = "Sun";
}
TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);
String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);
Joda-Time
I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:
import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);
or
DateTime date = DateTime().now();
Day of week (int):
date.getDayOfWeek();
Day of week (short String) using toString() and DateTimeFormat options:
date.toString("EE");
tl;dr
myGregCal // `GregorianCalendar` is a legacy class, supplanted by the modern `java.time.ZonedDateTime` class.
.toZonedDateTime() // Convert to `ZonedDateTime`.
.getDayOfWeek(). // Extract a `DayOfWeek` enum object, one of seven pre-defined objects, one for each day of the week.
.getDisplayName( // Automatically localize, generating a `String` to represent the name of the day of the week.
TextStyle.SHORT , // Specify how long or abbreviated.
Locale.US // Locale determines the human language and cultural norms used in localization.
) // Returns a `String` object.
Mon
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date for people in a certain region, without time-of-day and without time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Generate a string representing that day-of-week, localized using the human language and cultural norms of a particular locale.
lundi
java.time
Convert the troublesome old legacy java.util.GregorianCalendar object to a modern java.time object by calling new methods added to the old class.
ZonedDateTime zdt = myGregCal.toZonedDateTime();
Get the DayOfWeek enum object for that moment in that time zone.
DayOfWeek dow = zdt.getDayOfWeek();
dow.toString(): WEDNESDAY
Pass these DayOfWeek objects around your code rather than passing integers like 1-7 or strings like "MON". By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.
For presentation to the user, ask the DayOfWeek object to translate the name of the day of the week to a human language defined in a Locale.
String output =
dow.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.CANADA_FRENCH
)
;
mercredi
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….