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
Related
I'm pretty new to java programming and I'm suppose to read data from a separate text file in java and calculate the age of a person however I'm having trouble trying to get the calculation of the age right
Data in the text file:
First Name
Last Name
DOB (E.g. 15 Jan 1988)
Current Year (E.g. 2020)
Below is the code I'm using the read the data from the text file as well as the code I used to calculate the age however when I try to print the DOB it reads correctly but when I try to calculate it doesn't seem to do it correctly
String lastName = input.nextLine();
int day = input.nextInt();
Month month = Month.valueOf (input.next ()); //from an enum
int year = input.nextInt();
int currentYear = input.nextInt();
hr.setFirstName (firstName);
hr.setLastName (lastName);
d.setDate (day, month, year);
hr.setCurrentYear (currentYear);
//the method to calculate age from another class
public int getAge ()
{
Date d = new Date ();
int age = currentYear - d.getYear();
return age;
}
//code to print out the date of birth
System.out.printf("Date of birth: %d %s %d \n", d.getDay(), d.getMonth(), d.getYear());
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...
}
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
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]
This question has been asked many times but I have an issue which I feel makes it a unique question.
Here it goes.
I have a string which represents a two digit year i.e. to write 2016 I input 16
I have a requirement to convert a two digit year to four digit year i.e. 16 becomes 2016.
After going through some questions and answers I made the following findings
Solution 1
DateFormat sdfp = new SimpleDateFormat("dd.mm.yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
String date = sdff.format(d);
This would be great but I do not have a month or day in my case just a year and I could not find a way to create a date object with just the year.
Solution 2
The above could be solved with a Calendar object but it does not allow the input an of a two digit year for its year field.
Edit
Forgot to mention I cannot use Joda-Time because I'm working on the Android platform and it would increase the size of my project for just this small use
Why not just remove the part of month and day from the format?
DateFormat sdfp = new SimpleDateFormat("yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy");
String date = sdff.format(d);
LIVE
Here is the rule about how SimpleDateFormat interpret the abbreviated year. (bold by me)
For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created. For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964.
I think this is much simpler:
String year = "20" + input;
But if you want to make the user's life easy, and assume that he's entering a valid card, this problem is easy: if he types in 2 digits, then add (thisYear/100). If this seems to be in the past in the past, then if it's more than 90 years in the past, then add another 100 (this will only be the case in the last decade of any century)
Date now = new Date();
int expYear = (int)(now.getYear()/100) + parseInt(input);
if (expYear < now.getYear() && expYear+90<now.getYear()) {
expYear += 100;
}
public static int adjustOneOrTwoDigitYearInput(int year) {
return adjustOneOrTwoDigitYearInput(year, Year.now().getValue());
}
public static int adjustOneOrTwoDigitYearInput(int inputYear, int referenceYear) {
if(inputYear > 99) {
return inputYear;
}
int currentCentury = referenceYear / 100 * 100;
int currentCenturyYear = currentCentury + inputYear;
int upperLimit = referenceYear + 20;
int lowerLimit = referenceYear - 79;
// initially place it in current century
int adjusted = currentCenturyYear;
if(adjusted> upperLimit) {
// shift a century down
adjusted -= 100;
}
else if(adjusted < lowerLimit) {
// shift a century up
adjusted += 100;
}
return adjusted;
}
Some Testing:
#Test
public void test_adjustOneOrTwoDigitYearInput()
{
assertEquals(2017, adjustOneOrTwoDigitYearInput(17, 2017));
assertEquals(2037, adjustOneOrTwoDigitYearInput(37, 2017)); // +20
assertEquals(1938, adjustOneOrTwoDigitYearInput(38, 2017)); // +21
assertEquals(2000, adjustOneOrTwoDigitYearInput(0, 2017)); // 0
assertEquals(1999, adjustOneOrTwoDigitYearInput(99, 2017)); // 99
assertEquals(2078, adjustOneOrTwoDigitYearInput(78, 2078));
assertEquals(2098, adjustOneOrTwoDigitYearInput(98, 2078)); // + 20
assertEquals(1999, adjustOneOrTwoDigitYearInput(99, 2078)); // + 21 / 99
assertEquals(2000, adjustOneOrTwoDigitYearInput(0, 2078)); // 0
assertEquals(1990, adjustOneOrTwoDigitYearInput(90, 1990));
assertEquals(1999, adjustOneOrTwoDigitYearInput(99, 1990)); // 99
assertEquals(2000, adjustOneOrTwoDigitYearInput(0, 1990)); // 0
assertEquals(2010, adjustOneOrTwoDigitYearInput(10, 1990)); // +20
assertEquals(1911, adjustOneOrTwoDigitYearInput(11, 1990)); // +21
}
You could use Year from java.time if you are using java 8:
Year year = Year.parse("18", DateTimeFormatter.ofPattern("yy"));
year.toString(); //This returns 2018
You can also try something like this:
String input = "16";
String str = String.valueOf(Calendar.getInstance().get(Calendar.YEAR)).substring(0, 2)+input;
System.out.println("str = " + str);
And the result:
str = 2016
A rather simple one. Courtesy Gavriel
String year = "20" + input;
if(input>99)
{
String year= "2"+input;
}