Fetching only month from the date and giving month name in java - java

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".

Related

String input of weekdays in German to Localdate

I have a string input of weekdays in German and need to get the next Localdate after today which corresponds to the given weekday string. If for example the input is Montag (Monday) I need the output as Localdate of 2022-05-16 which is the next Monday after today. If the input was in english I could do something like:
String input = "Monday";
LocalDate today = LocalDate.now();
LocalDate nextWeekday = today.with(TemporalAdjusters.next(DayOfWeek.valueOf(input.toUpperCase())));
System.out.println(nextWeekday);
Is there something I can do, may be using Locale, to use strings (days) given in German to get the next weekday as a Localdate? If possible without defining my own Enum? I would want to avoid doing
public enum DayOfWeekGerman {
MONTAG,
DIENSTAG,
MITTWOCH,
...
//methods & getters
}
and map them somehow to use the java.time API methods like Localdate.with...
The classes of java.time are data classes. They do not have a locale. They happen to be English names only because the Java language itself is in English.
However, you can make a Map for looking up a DayOfWeek value from a name:
private static final Map<String, DayOfWeek> germanDaysOfWeek =
Arrays.stream(DayOfWeek.values()).collect(
Collectors.toMap(
d -> d.getDisplayName(TextStyle.FULL, Locale.GERMAN), d -> d));
{Freitag=FRIDAY, Samstag=SATURDAY, Montag=MONDAY, Mittwoch=WEDNESDAY, Donnerstag=THURSDAY, Dienstag=TUESDAY, Sonntag=SUNDAY}
Perform a lookup on that map.
String input = "Montag";
LocalDate today = LocalDate.now();
LocalDate nextWeekday = today.with(
TemporalAdjusters.next(germanDaysOfWeek.get(input)));
See all this code run live at Ideone.com.
2022-05-16
Considering today is 09/May/2022 (Monday), you can try :
String input = "Montag";
LocalDate today = LocalDate.now();
DayOfWeek weekday = DayOfWeek.from(
DateTimeFormatter.ofPattern("EEEE", Locale.GERMAN).parse(input));
LocalDate nextWeekday = today.with(TemporalAdjusters.next(weekday));
System.out.println(nextWeekday);
Output:
2022-05-16
If you execute it on any other day, you might get different output based on day & date.

How to convert date as string from 17-Dec-2018 to 2018-12-17 in java. I want to store it to MYSQL database

I have successfully imported date column from excel to the java code. However, I am unable to change the date format from 17-Dec-2018 to 2018-12-17. Kindly help.
public void saveToDatabase(Vector dataHolder) throws ParseException {
System.out.println(dataHolder);
for(Iterator iterator = dataHolder.iterator();iterator.hasNext();) {
List list = (List) iterator.next();
fullName = list.get(0).toString();
idNumberString = list.get(1).toString();
//idNumber = Integer.parseInt ( idNumberString );
committee = list.get(2).toString();
amountString = list.get(3).toString();
//amount = Integer.parseInt ( amountString );
bosaFosa = list.get(4).toString();
purpose = list.get(5).toString();
paymentsType = list.get(6).toString();
supportingDocuments = list.get(7).toString();
entryDate = list.get(8).toString();
}
The code now after fetching data from excel column the month is in text as "Dec" that is "17-Dec-2018"
I expect the final output in string as "2018-12-17" so that I can store in MYSQL database as DATE Type.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d-MMM-uuuu", Locale.ENGLISH);
String fullName = "Emmanuel Macron";
int idNumber = 42;
String entryDateString = "17-Dec-2018";
LocalDate entryDate = LocalDate.parse(entryDateString, dateFormatter);
PreparedStatement insertStatement = yourDbConnection.prepareStatement(
"insert into your_table (name, id, entry) values (?, ?, ?);");
insertStatement.setString(1, fullName);
insertStatement.setInt(2, idNumber);
insertStatement.setObject(3, entryDate);
int rowsInserted = insertStatement.executeUpdate();
The example is a bit simpler than yours, but should answer what you are asking about, so I trust the rest to you. I am using (and warmly recommending) java.time, the modern Java date and time API, for all date work in Java.
The steps involved for the date are:
Parse the date string into a LocalDate. LocalDate.parse(entryDateString, dateFormatter) does this. In the format pattern string, d-MMM-uuuu d means day of month in 1 or 2 digits, MMM means month abbreviation, and uuuu means 4 digit year. The month abbreviation is locale specific. Since I took Dec to be English, I have specified English locale for the formatter; please correct if your date strings are in some other language.
Pass the LocalDate to your PreparedStatement. insertStatement.setObject(3, entryDate); does this.
If you want to check that the first point worked as expected:
System.out.println("Entry date was parsed into " + entryDate);
Output:
Entry date was parsed into 2018-12-17
PS You may also want to check whether you can get the date from Excel in a different way. If you are using an older library such as Apache POI, I am afraid that the other option is an old-fashioned Date object, which you would then need to convert, so it’s a question whether it’s worth it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Your code is just simple. Here is code:
Parse string input.
String fromDate="17-Dec-2018";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(fromDate, dateFormatter);
Generate string output.
String convertedDate = localDate.toString();
System.out.println(convertedDate);
Here DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH) is the input date format and locale.
Here is the imports:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
EDIT:
Please follow the answer of #Ole V.V. given above as it is a better solution than mine.
You will first have to convert the String data into Date object.
Example code:
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
Then you can use SimpleDateFormat class to format date as you wish.
For more details on SimpleDateFormatter class, check this out

How can I change the language of the months provided by LocalDate?

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);

Reformatting a Date from DD-MMM-YYYY to YYYYDDMM or YYYYMMDD

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.

java.lang.IllegalArgumentException: Invalid format

This code:
DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss zzz").getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").getParser(), DateTimeFormat.forPattern("dd/MM/yyyy HH:mm").getParser(),
DateTimeFormat.forPattern("HH:mm").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
Session session;
DateTime dTime = null;
Calendar calendar;
try{
if (completedTime != null && !completedTime.equalsIgnoreCase("")){
LocalDateTime jt = LocalDateTime.parse(completedTime, formatter);
LocalDateTime dt;
LocalDateTime retDate;
produces the error:
java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 GDT" is malformed at " GDT"
at the LocalDateTime jt = LocalDateTime.parse(completedTime, formatter); line
I can't for the life of me work out why it is failing. I am pretty sure it is something simple, but I haven't spotted it.
You may want to refer to this thread (or one of the many others like it). My best advice would be to try cutting to only one "z" in your parser.
You need to manually specify a mapping from timezone abbreviation to timezone. For example:
return new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy HH:mm:ss ")
.appendTimeZoneShortName(UK_TIMEZONE_SYMBOLS)
.toFormatter();
Here UK_TIMEZONE_SYMBOLS is a Map<String,DateTimeZone> which contains our view of timezone names (so BST is British summer time, not Bangladesh standard time)
Here's how we build ours:
public static Map<String, String> buildTimeZoneSymbolMap(Locale locale) {
Map<String, String> timeZoneSymbols = Maps.newLinkedHashMap();
for (String[] zoneInfo : DateFormatSymbols.getInstance(locale).getZoneStrings()) {
String timeZone = zoneInfo[0];
if (!timeZoneSymbols.containsKey(zoneInfo[2])) {
timeZoneSymbols.put(zoneInfo[2], timeZone);
}
if (zoneInfo[4] != null && !timeZoneSymbols.containsKey(zoneInfo[4])) {
timeZoneSymbols.put(zoneInfo[4], timeZone);
}
}
timeZoneSymbols.put("UTC", "GMT");
return timeZoneSymbols;
}
public static Map<String, DateTimeZone> buildDateTimeZoneSymbolMap(Locale locale) {
return Maps.transformValues(buildTimeZoneSymbolMap(locale), input -> DateTimeZone.forTimeZone(TimeZone.getTimeZone(input)));
}
public static final Map<String, DateTimeZone> UK_TIMEZONE_SYMBOLS = ImmutableMap.copyOf(buildDateTimeZoneSymbolMap(Locale.UK));
First thing to note:
What is "GDT"? The website http://www.timeanddate.com/time/zones/ does not yield an answer. So if it really exists and is not a typo then what is your locale? Remember that time zone names and abbreviations are highly localized.
Second: The count of pattern symbols "z" is okay - for classes like SimpleDateFormat etc. - see its documentation. Either four letters for the full name or less than four letters for the abbreviation:
General time zone: Time zones are interpreted as text if they have
names. Text: For formatting, if the number of pattern letters is 4 or
more, the full form is used; otherwise a short or abbreviated form is
used if available. For parsing, both forms are accepted, independent
of the number of pattern letters.
But you use Joda-Time. Its documentation clearly states:
Zone names: Time zone names ('z') cannot be parsed.
I have verified this non-support using the newest Joda-Time version 2.7 by following code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss z").withLocale(Locale.GERMANY);
DateTime dt = formatter.parseDateTime("09/05/2015 04:00:00 MESZ");
System.out.println("Joda-Time: " + dt);
// Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 MESZ" is malformed at "MESZ"
Of course, "MESZ" is correct and must be interpreted as Europe/Berlin in context of given german locale.
However, since version update (2.2) the same code set to Locale.US works for some timezones names like "EDT", "PST" etc., see also this commit. So we can finally say, the parsing support of Joda-Time for timezone names and abbreviations is best to say very limited. Once again, what is your Locale? If it is not US then I can understand why you get the exception. And you will also get an exception for the input "GDT" even if we consider it as valid due to the limited capabilities of Joda-Time-parser.

Categories

Resources