Get the current week in Java [duplicate] - java

This question already has answers here:
Why do I get the "Unhandled exception type IOException"?
(6 answers)
java get week of year for given a date
(4 answers)
Closed 7 years ago.
I want to get the current week with a given date, e.g if the date is 2016/01/19, the result will be : week number: 3
I've seen some questions and answers about this but I'm not able to achieve what I want. Here is what I've done :
public static int getCurrentWeek() {
String input = "20160115";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
I've took this code from this question but I have an error on this line :
Date date = df.parse(input);
unhandled exception type ParseException

Use Java 8 LocalDate and WeekFields:
private int getCurrentWeek() {
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}

Look at this changed code:
String input = "20160115";
String format = "yyyyMMdd";
try {
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println("Input " + input + " is in week " + week);
return week;
} catch (ParseException e) {
System.out.println("Could not find a week in " + input);
return 0;
}
You need to catch ParseException and deal with it somehow. This could mean returning a "default" number (0 in this case) or passing the exception along (by declaring a throws on your method)

Related

I have created a method to add minutes to date time but does not as expected in Java [duplicate]

This question already has answers here:
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Why is the month changed to 50 after I added 10 minutes?
(13 answers)
Closed 3 years ago.
This is a java code where it adds the date with time hours and minutes if a possible day to
timeAddition("06/20/2019;23:30", 60, "m")
public static String timeAddition(String TimeAndDate, int addTime, String units_M_H) {
try {
String returnTime = TimeAndDate;
final long ONE_MINUTE_IN_MILLIS = 60000;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY;HH:mm");
Date date = dateFormat.parse(TimeAndDate);
Calendar Cal = Calendar.getInstance();
Cal.setTime(date);
if (units_M_H.trim().equalsIgnoreCase("h")) {
Cal.add(Calendar.HOUR_OF_DAY, addTime);
returnTime = dateFormat.format(Cal.getTime()).toString();
} else if (units_M_H.trim().equalsIgnoreCase("m")) {
long timeInMili = date.getTime();
date = new Date(timeInMili + (addTime * ONE_MINUTE_IN_MILLIS));
returnTime = dateFormat.format(date);
}
return returnTime;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The expected output is 06/21/2019;00:30 but the actual output is 12/31/2019;00:30
java.time
Do not reinvent the wheel, Java already has all instruments to do such operations. See the java.time package of classes built into Java. See Tutorial.
String timestamp = "06/20/2019;23:30";
LocalDateTime ldt = LocalDateTime.parse(timestamp,
DateTimeFormatter.ofPattern("MM/dd/yyyy;HH:mm"));
System.out.println(ldt);
LocalDateTime ldt2 = ldt.plus(60L, ChronoUnit.MINUTES);
System.out.println(ldt2);
Will print that you expect.
2019-06-20T23:30
2019-06-21T00:30
Hope this helps!
Use yyyy for year.
YYYY represents week year.

How to convert person mm/dd/yyyy D.O.B into actual age. Selenium, Java [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
How do I calculate someone's age in Java?
(28 answers)
How can I calculate age in Java accurately given Date of birth
(4 answers)
Closed 4 years ago.
I want to convert date of birth into age.
This is my code.
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
I'm getting date as: 03/01/1961
How could I convert this into age?
I want output like => 57 Years
Any idea? :)
using java 8
public int calculateAge(
LocalDate birthDate) {
// validate inputs ...
return Period.between(birthDate, LocalDate.now());
}
private static final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
Date dateOfBirth = getDateFromString(patientDOB);
public Date getDateFromString(final String patientDOB) {
try {
return FORMATTER.parse(param);
} catch (ParseException e) {
throw new Exception("ParseException occurred while parsing date ", e);
}
}
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("You don't exist yet");
}
int todayYear = today.get(Calendar.YEAR);
int birthDateYear = birthDate.get(Calendar.YEAR);
int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
int birthDateDayOfYear = birthDate.get(Calendar.DAY_OF_YEAR);
int todayMonth = today.get(Calendar.MONTH);
int birthDateMonth = birthDate.get(Calendar.MONTH);
int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int birthDateDayOfMonth = birthDate.get(Calendar.DAY_OF_MONTH);
int age = todayYear - birthDateYear;
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ((birthDateDayOfYear - todayDayOfYear > 3) || (birthDateMonth > todayMonth)){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
} else if ((birthDateMonth == todayMonth) && (birthDateDayOfMonth > todayDayOfMonth)){
age--;
}
return age;
}
Create a wrapper method that get you string as argument,
use:
String[] parts = string.split("/");
and select the 3rd item of the list.
then you just have to use:
int year = Calendar.getInstance().get(Calendar.YEAR);
to get your year. Then you just convert your year string into an int and substract them

How to get day of year as an integer with simpledateformat? [duplicate]

This question already has answers here:
Today is nth day of year [duplicate]
(6 answers)
Julian day of the year in Java
(9 answers)
Closed 4 years ago.
I have a simple program that asks a user to enter a date in a MM-dd-yyyy format. How can I get the day of the year from this input? For example if the user enters "06-10-2008" the day of the year would be the 162nd day considering this was a leap year.
Here's my code so far:
System.out.println("Please enter a date to view (MM/DD/2008):");
String date = sc.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date2=null;
try {
//Parsing the String
date2 = dateFormat.parse(date);
} catch (ParseException e) {
System.out.println("Invalid format, please enter the date in a MM-dd-yyyy format!");
continue;
} //End of catch
System.out.println(date2);
}
Assuming you are using Java 8+, you could use the LocalDate class to parse it with a DateTimeFormatter like
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());
Outputs (as requested)
162
Like this
Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
Calendar c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));

Wrong date is getting printed [duplicate]

This question already has answers here:
Java date format conversion - getting wrong month
(8 answers)
Getting wrong month when using SimpleDateFormat.parse
(3 answers)
Closed 5 years ago.
I am trying to simply pass a date and parse it using simpledateformat. But instead of printing the correct value, it's printing wrong date.
public static void main(String[] args) {
getAge("29-02-2016");
}
public static void getAge(String dob1) {
DateFormat format = new SimpleDateFormat("dd-mm-yyyy");
try {
Date dob = format.parse(dob1);
System.out.println(dob);
Calendar realDob = Calendar.getInstance();
realDob.setTime(dob);
System.out.println(realDob.get(Calendar.YEAR));
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - realDob.get(Calendar.YEAR);
if(age >=18) {
System.out.println("18 years");
} else {
System.out.println("Underage");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
its printing : Fri Jan 29 00:02:00 IST 2016 but it should be February
mm is for minutes, use MM: DateFormat format = new SimpleDateFormat("dd-MM-yyyy");

How to get month and day from given string? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
How can I get day and date from given Strings. For example:
String date="25-12-2014";
How to get date and day from given string?
Expected output is,
25
Thu
I got stuck when I tried this.
private static String getFormatedDate(String strDate) {
String result = "";
if(strDate != null) {
if (strDate.contains("-")) {
String[] dates = strDate.split("-");
for(int i=0;i<dates.length;i++) {
result = result + Utils.replaceDateFormat(dates[i].trim(),"MMM dd", "EE, M.dd") + ("-");
}
int lastIndex = result.lastIndexOf("-");
result = result.substring(0, lastIndex).trim();
}
else {
result = Utils.replaceDateFormat(strDate.trim(),"MMM dd", "EE, M.dd");
}
}
return result;
}
Utils:
public static String replaceDateFormat(String value, String actualFormat, String exceptedFormat) {
final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
final SimpleDateFormat fromDate = new SimpleDateFormat(actualFormat);
final SimpleDateFormat toDate = new SimpleDateFormat(exceptedFormat);
Date convertedFromDate = null;
try {
convertedFromDate = fromDate.parse(value);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
final Calendar c1 = Calendar.getInstance();
c1.setTime(convertedFromDate);
c1.set(Calendar.YEAR, currentYear);
return toDate.format(c1.getTime());
}
Your methods are very convoluted for a relatively simple task. Why don't you use SimpleDateFormat? You can use the parse method. For example:
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(string);
And then you can get the required fields from there.
EDIT
To get the day of the week, you were right with this code:
Date d = date.parse(result);
Calendar c = Calendar.getInstance();
c.setTime(d);
int day=c.get(Calendar.DAY_OF_WEEK);
And then if you want it in the format above, you could just make an array filled with the days of the week:
String[] daysOfWeek = new String[]{"Sun","Mon"... etc}
String day = daysOfWeek[day - 1];
You can use the method from Calendar:
String date = "25-12-2014";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse(date));
int day = cal.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getShortWeekdays();
System.out.printf("%02d %3s\n", day, days[dayOfWeek]);
The symbols can be set to your Locale zone.
if you are allowed to use java 8 you can give LocalDate a chance:
String date = "25-12-2014";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek());
Output is:
25, THURSDAY
EDIT:
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek().substring(0, 3));
#No aNoNym suggestion is right, with the following you get
25, THU

Categories