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

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]

Related

Need help parsing string date [duplicate]

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

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

Simple one class program java intro trouble [duplicate]

This question already has an answer here:
Java: how can i add a day on Date? [duplicate]
(1 answer)
Closed 5 years ago.
I've been working on this for hours, and while this is due tonight I got my wisdom teeth out today and the anesthesia is making me really easily confused.
I need is two methods within the class, "toString", which takes dd/mm/yyyy and prints that, as well as "advance" which modifies the day + 1.
When I check the modified date, I receive this:
Initial date: 88/8/8888
Modified date: 88/0/8888
int day, month, year, newDay;
String decision, dummy ;
Scanner read = new Scanner(System.in);
public static void main(String[] args) {
Date dateInstance = new Date();
dateInstance.toString();
dateInstance.advance();
}
public String toString() {
System.out.println("Enter day (mm/xx/yyyy): ");
day = read.nextInt();
System.out.println("Enter month (xx/dd/yyyy): ");
month = read.nextInt();
System.out.println("Enter year (mm/dd/xxxx): ");
year = read.nextInt();
System.out.println("Initial date: "+month+"/"+day+"/"+year);
System.out.println("Modified date: "+month+"/"+newDay+"/"+year);
return null;
/*
String decision = read.nextLine();
System.out.println("Would you like to display the date, and the modified date? (Y / N): ");
if(decision == "N") {
System.out.println("'N' Selected");
}else if(decision == "Y") {
System.out.println("Initial date: "+month+"/"+day+"/"+year);
System.out.println("Modified date: "+month+"/"+newDay+"/"+year);
}
return dummy;
*/
}
public int advance() {
newDay = day + 1;
return newDay;
}
Here is some code to get you started. I would guess that your teacher doesn't want you to rewrite the Date's toString() method but actually use it to create your own function that displays the output in another format (Hint - opposite).
Date dateInstance = new Date(System.currentTimeMillis());
Date dateForward = new Date(dateInstance.getTime() + 1000*60*60*24); //put this in a method
System.out.println(dateInstance.toString()); //use the split method to extract and rearrange the date
System.out.println(dateForward.toString());
Check out the Java 8 Docs for the Date Object
Output
2017-06-29
2017-06-30

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)

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