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);
Related
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));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
If I have the age of a person, and the current day and month are the same as the birthdate, how can I calculate the birthyear with Java 8?
For example:
Age = 30 years
Current date = July 1st, 2019
Expected output = July 1st, 1989
tl;dr
In other words, you want to subtract a number of years from a date.
LocalDate
.of( 2019 , Month.JULY , 1 )
.minusYears( 30 )
See this code run live at IdeOne.com.
1989-07-01
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
MonthDay
I have a hunch what you really need is MonthDay to represent the idea of an annual birthday, just the month and the day-of-month but without a year.
From a MonthDay object you can determine a date for any year, generating a LocalDate object. Use Year class to get current year.
MonthDay birthMonthDay = MonthDay.of( Month.JANUARY , 23 ) ;
LocalDate birthDateSomeYear = birthMonthDay.atYear( 2010 ) ;
LocalDate birthDateThisYear = birthMonthDay.atYear( Year.now( z ).getValue() ) ;
A month-day of February 29th will be adjusted to February 28th in a non-leap year.
Date math
You can subtract a number of years from a LocalDate, producing a new LocalDate object.
int ageInYears = 37 ;
LocalDate then = someLocalDate.minusYears( ageInYears ) ;
If you meant you have the age in a finer resolution of years-months-days, use Period class.
Period p = Period.of( 37 , 4 , 2 ) ; // years-months-days.
Do the math.
LocalDate ld = someLocalDate.minus( p ) ;
I am beginner for Java, so asked. but I got solution. Thank you guys for suggestion.
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int age = 30;
Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dayOfYear = cal.get(Calendar.YEAR);
int birthYear = dayOfYear - age;
System.out.println(birthYear);
// using local time
LocalDate todayDate = LocalDate.now();
int y = todayDate.getYear();
int birthYearFromTime = y-age;
System.out.println(birthYearFromTime);
}
}
I have to fetch hours and minutes from time format I am getting from the system however it is showing me error like int month= moment.Month;
DateTime productDate = DateTime.Now;
string twentyFourHourFormatHour =int.Parse(productDate.ToString("HH")).ToString();
Not picking up productdate when trying to store it in string (line 2)
DateTime has properties to expose all of the data you need. There is no need to do elaborate string manipulation.
DateTime date = DateTime.Now();
int hour = date.Hour;
int minute = date.Minute;
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);
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;
}