How to get next year date from the user entered date in java - java-7

Below is the code that returning wrong date
String dt = "01-08-2021";
SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
Date date = new SimpleDateFormat("dd-mm-yyyy").parse(dt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
cal.add(Calendar.YEAR, 1);
date = cal.getTime();
System.out.println(format.format(date));
It printing as 31-08-2021, it suppose to print 31-07-2022.
If I pass 02-08-2021, it working perfectly 01-08-2022
I am using java1.7. Can anyone help me on this.

Not sure whether thats the issue... but: you're using the SimpleDateFormat wrong. MM stands for month. mm stands for Minute. See here: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

You do not need line - cal.add(Calendar.DATE, -1) in your code.
You can try below code, it working fine
String dt = "01-08-2021";
SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
Date date = new SimpleDateFormat("dd-mm-yyyy").parse(dt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, 1);
date = cal.getTime();
System.out.println(format.format(date));

Related

How to get TimeZone offset value in java

I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.

NSDateFormatter have extra dot in front of month for nb_NO (Norsk Bokmal) locale

I'm working in a Xamarin.IOs project. I'm trying to convert a DateTime object into the following format "dd. MMM yyyy" under "nb_NO" locale which should return something like, Ex: "05. feb 2018".
I'm using the following code snippets to achieve this, (C#)
var now = DateTime.Now;
var format = "dd. MMM yyyy";
var formatter = new NSDateFormatter { DateFormat = format, Locale = new NSLocale("nb_NO"), TimeZone = NSTimeZone.SystemTimeZone };
var nsDate = DateTimeToNSDate(now);
var formattedDate = formatter.StringFor(nsDate);
But what I get for formattedDate is something like Ex: "05. feb. 2018". There is an extra dot (period) after the month as well.
What can I do to get rid of this unexpected extra dot after the month in "nb_NO" locale?
After a long research, I tried the following string format, "dd. LLL yyyy".
You have to use LLL instead of MMM to render the month.
This just solved me the issue.
You can find all the possible formats here!

java.time.format.DateTimeParseException: Text could not be parsed at index 3

I am using Java 8 to parse the the date and find difference between two dates.
Here is my snippet:
String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";
DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
When I run I get the error:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.
Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).
So, your formatter should be created like this:
DateTimeFormatter df = new DateTimeFormatterBuilder()
// case insensitive to parse JAN and FEB
.parseCaseInsensitive()
// add pattern
.appendPattern("dd-MMM-yyyy")
// create formatter (use English Locale to parse month names)
.toFormatter(Locale.ENGLISH);
This will make your code work (and datediff will be 32).
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".
String date1 ="01-Jan-2017";
String date2 = "02-Feb-2017";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/
// DateTimeFormatterBuilder provides custom way to create a
// formatter
// It is Case Insensitive, Nov , nov and NOV will be treated same
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
System.out.println(datetime); // 2019-12-22
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
Maybe Someone is looking for this it will work with date Format like 3/24/2022 or 11/24/2022
DateTimeFormatter.ofPattern("M/dd/yyyy")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
formatter = formatter.withLocale( Locale.US ); // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("3/24/2022", formatter);
System.out.println(date);
Maybe you can use this wildcard,
String d2arr[] = {
"2016-12-21",
"1/17/2016",
"1/3/2016",
"11/23/2016",
"OCT 20 2016",
"Oct 22 2016",
"Oct 23", // default year is 2016
"OCT 24", // default year is 2016
};
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient()
.parseDefaulting(ChronoField.YEAR_OF_ERA, 2016L)
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[M/dd/yyyy]")
.appendPattern("[M/d/yyyy]")
.appendPattern("[MM/dd/yyyy]")
.appendPattern("[MMM dd yyyy]");
DateTimeFormatter formatter2 = builder.toFormatter(Locale.ENGLISH);
https://coderanch.com/t/677142/java/DateTimeParseException-Text-parsed-unparsed-textenter link description here
Try using DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-LLL-yyyy",Locale.ENGLISH);

How to find date lies in which week of month

Suppose I have a date in year-month-day format. Say "2015-02-12". Now I want to find that in which week this date lies. I mean 12 lies in 2nd week of Funerary. I want if I fo something like
LocalDate date = 2015-02-12;
date.getWeekOfMoth should gives me 2 because 2 lies in 2nd week of February. How can i do it ?
Thanks
Edit
Hi, I am so sorry. I should replied you before you asked. I tried with the following code
String input = "2015-01-31";
SimpleDateFormat df = new SimpleDateFormat("w");
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_MONTH);
System.out.println(week);
It prints 2.
While when I check with the following code
String valuee="2015-01-31";
Date currentDate =new SimpleDateFormat("yyyy-MM-dd").parse(valuee);
System.out.println(new SimpleDateFormat("w").format(currentDate));
It prints 5.
Try this one. Remember to feed it with your date format and string with this date as input.
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_MONTH);

Why is my DateTime now giving me the month and the date of the month?

I’m doing the code below in my view but I just get the month and number of the month in regards to 12 months of the year like this:
May 5 instead of May 14.
Here’s the code I have in my view:
#{
DateTime now = DateTime.Now;
String date = now.ToString("MMM");
}
What I want is the month and the date of the month. What am I doing wrong here?
Try
#{
DateTime now = DateTime.Now;
int month = now.Month;
string monthName=now.ToString("m").Split(' ')[1];
int day=now.Day;
}

Resources