Need help parsing string date [duplicate] - java

This question already has answers here:
How to extract day, month and year from Date using Java? [duplicate]
(2 answers)
Split date/time strings
(7 answers)
Converting string to date using java8
(3 answers)
I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?
(8 answers)
Java string to date conversion
(17 answers)
Closed 2 years ago.
So far I have the first month figured out but I still need help with the day and year. I am having trouble parsing the individual pieces and converting them to integers.
int firstSlash = date.indexOf ("/");
month = Integer.parseInt (date.substring (0, firstSlash));
That is what I have so far.

Easy way
There is a function called split() that takes the delimiter and returns an array of strings:
String[] words = date.split("/");
int month = Integer.parseInt(words[0]);
int day = Integer.parseInt(words[1]);
int year = Integer.parseInt(words[2]);
Correct way
When it comes to parsing date from string, the preferred way is using Java DateFormat API:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date theDate = format.parse(date);
Date object is much more powerful and allows you to interact with date and time much more fluently than bare ints
More info here!

If you know where are your month, year and day like : 25/10/2020 you can just use the split function
If you are SURE that the date will be in the right format :
String[] dateSplit = date.split("/");
int day = Integer.valueOf(dateSplit[0]);
int month = Integer.valueOf(dateSplit[1]);
int year = Integer.valueOf(dateSplit[2]);
System.out.println("year" + year);
System.out.println("month" + month);
System.out.println("day" + day);
If you are NOT SURE that the date will be in the right format :
String[] dateSplit = date.split("/");
if (dateSplit.length != 3) {
throw new Exception("Date not in valid format");
//or do something else like printing or whatever...
}
try {
int day = Integer.valueOf(dateSplit[0]);
int month = Integer.valueOf(dateSplit[1]);
int year = Integer.valueOf(dateSplit[2]);
System.out.println("year" + year);
System.out.println("month" + month);
System.out.println("day" + day);
} catch (NumberFormatException e) {
throw new Exception("Date not in valid format");
//or do something else like printing or whatever...
}

Related

I want to Add Months In date like 6/5/2021 to 6/6/2021, but there is only increment in Days but not in Month and Year [duplicate]

This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 1 year ago.
I want to add 2 Months in another Date but he only add 60 Days in Date and there is no increment in Months of the Date as well as in Year.
I'm using following code for adding Date in another Date. Days adding correctly but there is no increment in Month of Date. if I add 60 Days then he add but again there is no increment in Month as well as in Year. If someone help me to resolve problem then I really thank full!!!
String dob = "06/05/2021";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dob));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 60);
c.add(Calendar.MONTH,2); // Not Working
sdf = new SimpleDateFormat("dd/mm/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
String incToDate = sdf.format(resultdate);
Toast.makeText(this, incToDate, Toast.LENGTH_SHORT).show();
Your pattern is not correct, it basically reads two digits for day of month/two digits for minute of hour/4 digits for year. I'm guessing you did not want any minutes of hour in this pattern, so change the lower-case ones to upper-case ones.
If you can use java.time, you could get the desired result like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// provide an example date as String
String dob = "06/05/2021";
// create a formatter that can parse a String in the given format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// parse the String to a LocalDate using the previously defined formatter
LocalDate localDob = LocalDate.parse(dob, dtf);
// print the (formatted) result just to see if parsing has worked
System.out.println("Just parsed " + localDob.format(dtf));
// add two months and print a result phrase
LocalDate localDobTwoMonthsLater = localDob.plusMonths(2);
System.out.println("Adding two months results in "
+ localDobTwoMonthsLater.format(dtf));
// for completeness, add 60 days and print the result
LocalDate localDobSixtyDaysLater = localDob.plusDays(60);
System.out.println("Adding sixty days results in "
+ localDobSixtyDaysLater.format(dtf));
}
}
This code prints
Just parsed 06/05/2021
Adding two months results in 06/07/2021
Adding sixty days results in 05/07/2021

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

String.split("-") not working [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I have a method that calculates age; calculateAge(User user):
public int calculateAge(User user) {
String date = null, month = null, year = null;
String[] fields;
String DOB = user.getDOB();
System.out.println(DOB);
fields = DOB.split("-");
System.out.println(fields);
fields[0] = date;
fields[1] = month;
fields[2] = year;
System.out.println(date);
System.out.println(month);
System.out.println(year);
LocalDate birthDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(date));
LocalDate now = LocalDate.now();
Period age = Period.between(birthDate, now);
return age.getYears();
}
The prints are debugging lines, and as of now, this is what they print:
The DOB is 1-1-1988, but fields is [Ljava.lang.String;#6d41a4a instead of displaying the array of fields. As such, date, month, and year are printed as null and it can't Integer.parseInt(null), so it gives me a NumberFormatException: null.
That output is just Java's standard way of printing an array.
You just got your assignment the wrong way around, I think.
I guess it should be
date = fields[0]
months = fields[1]
year = fields[2]

Get the current week in Java [duplicate]

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)

Categories