I need to find the current month and print it. I have the following code:
this.currentDate=LocalDate.now();
this.month = this.currentDate.getMonth();
The problem is that the month is in English and I need to print it in French, to match the rest of the website language. How can I select the language of the month provided by the LocalDate.now() method without needing to do a manual translation each time I need to display it?
You can convert the Month type into a String using getDisplayName(), which can change the locale to French as follows:
this.currentDate = LocalDate.now();
this.month = this.currentDate.getMonth().getDisplayName(TextStyle.FULL, Locale.FRANCE);
You can use the DateTimeFormatter to create a formatter for French as follows:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, dd MMMM, yyyy", Locale.FRENCH);
final String month = LocalDate.now().format(formatter);
Related
I have fetched the date month and year from the text file so now i want to fetch only month part and I have to get month name I have done like this
String s;
String keyword = "Facture du";
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
// s= s.replaceAll("\\D+","");
System.out.println(s);
}
}
Actual Output: Facture du 28/05/2018
Expected Output: only Month name
Using java-8's LocalDate you can just do :
String strDate = "28/05/2018";
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.parse(strDate, format);
System.out.println(localDate.getMonth());
which gives the output as MAY
Nicholas K already provided an answer nicely showing the use of java.time. I just wanted to add that java.time can do a bit more than shown there.
DateTimeFormatter factureLineFormatter
= DateTimeFormatter.ofPattern("'Facture du' dd/MM/uuuu");
String keyword = "Facture du";
String s = "Facture du 28/05/2018";
if (s.contains(keyword)) {
LocalDate date = LocalDate.parse(s, factureLineFormatter);
Month month = date.getMonth(); // Extract a `Month` enum object.
String output =
month.getDisplayName( // Get localized name of month.
TextStyle.FULL, // How long or abbreviated should the month name be.
Locale.FRENCH) // `Locale` determines the human language used in translation, and the cultural norms used in abbreviation, punctuation, and capitalization.
;
System.out.println(output);
}
Output:
mai
I am parsing the entire line immediately by adding the literal text in quotes in the format pattern string. I am printing the localized month name — here in French, but you can choose another language. You may also choose to have it abbreviated if you prefer.
Edit: Basil Bourque has kindly edited my code spelling out in comments what each method and argument does. This makes the code look long, but is great for the explanation in a Stack Overflow answer. In production code you would probably use a one-liner:
System.out.println(date.getMonth().getDisplayName(TextStyle.FULL, Locale.FRENCH));
You could use Calendar from the java.utils package:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("28/05/2018");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.getDisplayName(Calendar.MONTH, Calendar.LONG_FORMAT, Locale.FRENCH));
I'm assuming you speak french and want to display the french name. Otherwise you will need to adjust the Locale parameter.
For your date this code will output "mai".
Java code to create date from given day of week, week of month, month and year as input. Example- if the iputs are as below:
day-Monday, month-july, week-1, year-2018,
then output should be-02/07/2018.
Below is the code used:
System.out.println("Enter a year,month,week,day:");
int year = Integer.parseInt(obj.nextLine());
int month = Integer.parseInt(obj.nextLine());
int week = Integer.parseInt(obj.nextLine());
String day = obj.nextLine();
String date;
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year); // set the year
cal.set(Calendar.MONTH, month-1); // set the month
cal.set(Calendar.WEEK_OF_MONTH, week);
//***error in the below line********
cal.set(Calendar.DAY_OF_WEEK,day);
date=dateFormat.format(cal.getTime());
System.out.println("Result:" +date);
The marked line won’t compile. Why not? How should I fix it?
The bit you seem to be missing is that when the user enters for example “Monday”, you need to convert this string into something that Java can understand as a day of week. This is done through parsing. Fortunately using java.time, the modern Java date and time API, it is not so hard (when you know how). This is what we use the dowFormatter for in the following code (dow for day of week):
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
DateTimeFormatter dowFormatter
= DateTimeFormatter.ofPattern("EEEE", Locale.getDefault(Locale.Category.FORMAT));
DayOfWeek dow = DayOfWeek.from(dowFormatter.parse(day));
WeekFields wf = WeekFields.of(Locale.getDefault(Locale.Category.DISPLAY));
LocalDate date = LocalDate.of(year, month, 15)
.with(dow)
.with(wf.weekOfMonth(), week);
System.out.println("Result: " + date.format(dateFormatter));
Now when I enter 2018, 7, 1 and Monday, I get:
Result: 2018/07/02
If you want to control in which language the user should enter the day of week, pass the appropriate locale to the formatter (instead of Locale.getDefault(Locale.Category.FORMAT)). If you want it to work in English only, you may use the shorter DayOfWeek dow = DayOfWeek.valueOf(day.toUpperCase(Locale.ROOT));, but it’s a bit of a hack.
If you want to control the week scheme used, pass the appropriate locale to WeekFields.of() or just specify WeekFields.ISO or WeekFields.SUNDAY_START.
I recommend that you don’t use SimpleDateFormat and Calendar. Those classes are long outdated. java.time is much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I'm trying to use Java 8 to re-format today's date but I'm getting the following error:
java.time.format.DateTimeParseException: Text '09-OCT-2017' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=10, DayOfYear=9},ISO of type java.time.format.Parsed
Code:
public static String formatDate(String inputDate, String inputDateFormat, String returnDateFormat){
try {
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(inputDateFormat).toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(returnDateFormat);
String formattedString = localDate.format(outputFormatter);
return formattedString;
} catch (DateTimeParseException dtpe) {
log.error("A DateTimeParseException exception occured parsing the inputDate : " + inputDate + " and converting it to a " + returnDateFormat + " format. Exception is : " + dtpe);
}
return null;
}
I previously tried using SimpleDateFormat, but the problem is my inputDateFormat format is always in uppercase DD-MMM-YYYY, which was giving me incorrect results, so I tried using parseCaseInsensitive() to ignore the case sensitivity.
In the comments you told that the input format is DD-MMM-YYYY. According to javadoc, uppercase DD is the day of year field, and YYYY is the week based year field (which might be different from the year field).
You need to change them to lowercase dd (day of month) and yyyy (year of era). The parseCaseInsensitive() only takes care of the text fields - in this case, the month name (numbers are not affected by the case sensitivity - just because the month is in uppercase, it doesn't mean that the numbers patterns should also be).
The rest of the code is correct. Example (changing the format to yyyyMMdd):
String inputDate = "09-OCT-2017";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// use "dd" for day of month and "yyyy" for year
.appendPattern("dd-MMM-yyyy")
.toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);
// use "dd" for day of month and "yyyy" for year
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String formattedString = localDate.format(outputFormatter);
System.out.println(formattedString); // 20171009
The output of the code above is:
20171009
Regarding your other comment about not having control over the input pattern, one alternative is to manually replace the letters to their lowercase version:
String pattern = "DD-MMM-YYYY";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// replace DD and YYYY with the lowercase versions
.appendPattern(pattern.replace("DD", "dd").replaceAll("YYYY", "yyyy"))
.toFormatter(Locale.ENGLISH);
// do the same for output format if needed
I don't think it needs a complex-replace-everything-in-one-step regex. Just calling the replace method multiple times can do the trick (unless you have really complex patterns that would require lots of different and complex calls to replace, but with only the cases you provided, that'll be enough).
I hope I got you right.
Formatting a String to LocalDate is acutally pretty simple. Your date format is that here right 09-Oct-2017?
Now you just need use the split command to divide that into a day, month and year:
String[] tempStr = inputDate.split("-");
int year = Integer.parseInt(tempStr[2]);
int month = Integer.parseInt(tempStr[1]);
int day = Integer.parseInt(tempStr[0]);
After that it´s pretty easy to get that to LocalDate:
LocalDate ld = LocalDate.of(year, month, day);
I hope that helps.
i am developing a Google-Calendar alike using Zk-Calendar i have a question about java.text.SimpleDateFormat here is some code
1). how to get the day and month in first letter uppercase is this possible?
here is the code i'm using so far.
private final SimpleDateFormat dformat = new SimpleDateFormat("EEEE dd-MMMMM-yyyy HH:mm:ss a");
private void printDateTester()
{
final Locale VENEZUELA_LOCALE = new Locale("es","VE");
Locale locale = Locale.getDefault();
System.out.println(locale.getDisplayCountry()+" "+locale.getCountry());//prints United States US
System.out.println(VENEZUELA_LOCALE.getDisplayCountry()+" "+VENEZUELA_LOCALE.getCountry());//prints Venezuela VE
final Calendar TODAY_US = Calendar.getInstance(locale);
final Calendar TODAY_VEN = Calendar.getInstance(VENEZUELA_LOCALE);
System.out.println(dformat.format(TODAY_US.getTime())); //prints sábado 10-agosto-2013 11:07:55 AM
System.out.println(dformat.format(TODAY_VEN.getTime()));//prints sábado 10-agosto-2013 11:07:55 AM
}
it prints something like sabado 10-agosto-2013 09:42:24 AM in english something like saturday 10-august-2013 but i would like something like Saturday 10-August-2013 09:42:24 AM is this possible?
any ideas thanks a lot.
UPDATE
i have create 2 SimpleDateFormats 1 using Locale.US and 2 other using either Venezuela Locale and Spain Locale the US version prints in Uppercase but both Venezuela and Spain locales prints in lowercase but i need show the data in Spanish why is this??
final Locale VENEZUELA_LOCALE = new Locale("es","VE");
Locale locale = Locale.getDefault();
final SimpleDateFormat dformatI = new SimpleDateFormat("EEEE dd-MMMMM-yyyy HH:mm:ss a",VENEZUELA_LOCALE);
final SimpleDateFormat dformatII = new SimpleDateFormat("EEEE dd-MMMMM-yyyy HH:mm:ss a",Locale.US);
Locale: Venezuela VE
print: domingo 11-agosto-2013 09:24:25 AM
Locale: United States US
print: Sunday 11-August-2013 09:24:25 AM
Have you tried setting Locale in DateTime format object:
private final SimpleDateFormat dformat = new SimpleDateFormat("EEEE dd-MMMMM-yyyy HH:mm:ss a",Locale.US);
Not all languages are following US standard (Capitalized day and month names). Therefore what output value java DateTimeFormat is giving was expected.
You could find this interesting discussion in the following questions
How to control the capitalization of month and day names returned by DateFormat?
I need to build a date format like dd/MM/yyyy. It's almost like DateFormat.SHORT, but contains 4 year digits.
I try to implement it with
new SimpleDateFormat("dd//MM/yyyy", locale).format(date);
However for US locale the format is wrong.
Is there a common way to format date that changes pattern based on locale?
Thank you
I would do it like this:
StringBuffer buffer = new StringBuffer();
Calendar date = Calendar.getInstance();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
StringBuffer format = dateFormat.format(date.getTime(), buffer, yearPosition);
format.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), String.valueOf(date.get(Calendar.YEAR)));
System.out.println(format);
Using a FieldPosition you don't really have to care about wheter the format of the date includes the year as "yy" or "yyyy", where the year ends up or even which kind of separators are used.
You just use the begin and end index of the year field and always replace it with the 4 digit year value and that's it.
java.time
Here’s the modern answer. IMHO these days no one should struggle with the long outdated DateFormat and SimpleDateFormat classes. Their replacement came out in the modern Java date & time API early in 2014, the java.time classes.
I am just applying the idea from Happier’s answer to the modern classes.
The DateTimeFormatterBuilder.getLocalizedDateTimePattern method generates a formatting pattern for date and time styles for a Locale. We manipulate the resulting pattern string to force the 4-digit year.
LocalDate date = LocalDate.of( 2017, Month.JULY, 18 );
String formatPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
userLocale);
formatPattern = formatPattern.replaceAll("\\byy\\b", "yyyy");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale);
String output = date.format(formatter);
Example output:
For Locale.US: 7/18/2017.
For each of UK, FRANCE, GERMANY and ITALY: 18/07/2017.
DateTimeFormatterBuilder allows us to get the localized format pattern string directly, without getting a formatter first, that’s convenient here. The first argument to getLocalizedDateTimePattern() is the date format style. null as second argument indicates that we don’t want any time format included. In my test I used a LocalDate for date, but the code should work for the other modern date types too (LocalDateTime, OffsetDateTime and ZonedDateTime).
I have similar way to do this, but I need to get the locale pattern for the ui controller.
So here's the code
// date format, always using yyyy as year display
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
SimpleDateFormat simple = (SimpleDateFormat) dateFormat;
String pattern = simple.toPattern().replaceAll("\\byy\\b", "yyyy");
System.out.println(pattern);
Can you not just use java.text.DateFormat class ?
DateFormat uk = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
DateFormat us = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
Date now = new Date();
String usFormat = us.format(now);
String ukFormat = uk.format(now);
That should do what you want to do.