Formatting user input in Java to date - java

I am having some difficulty understanding the way to change a user input of dates an an int to be compared to another int.
Am trying to get the user to input his date of birth, then compare it to zodiac signs dates in a switch format if it is possible.
Going through most of the post on how to change an input to int, with pars, and SimpleDateFormat I was not able to apply it, as shown in my code when I try to implement "dateOB" that should've been formated to an int, in the switch statement it did not recognize it as so ...
My code so far:
import java.util.*;
import java.text.*;
public class signs {
public static void main(String[] args) {
Scanner userInput = new Scanner (System.in);
// Intro message
System.out.println("Hello you, Lets get to know each other");
// User input begin
//name
String userName;
System.out.println("What is your name ?");
userName = userInput.nextLine();
//date of birth
System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
String dateOB = userInput.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
try {
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println(dateOB);
} catch (ParseException e) {
e.printStackTrace();
return;
}
System.out.println("So your date of birth is " + dateOB);
// choosing zodiac sign
//starting the switch statement
int convertedDate = dateOB;
String zodiacSign;
switch (convertedDate){
}
}
}
I would appreciate it if someone could explain to me how to implement this in a simple way ...
So i get really great suggestion by you guys, and i ended up with the right understanding of things, just complication implementing minor suggestion to make the code function the right way,
what i got so far is :
boolean correctFormat = false;
do{
System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
String dateOB = userInput.next();
try{
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println(dateOB);
System.out.println("So your date of birth is " + dateOB);
correctFormat = true;
}catch(ParseException e){
correctFormat = false;
}
}while(!correctFormat);
So the problem i am facing is that " dateOB is now since it is inside a while loop, is not recognized out side the loop, which is checking if the date format is right , so when i try and conver the date to a number :
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(dateOB));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
//int month = cal.get(Calendar.MONTH)+ 1;
it is not accepted ?
how do i tackle this issue ?
Hey so far i've been having some trouble with part of the code:
Calendar cal = Calendar.getInstance();
cal.setTime(dayNmonth);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH)+ 1;
as in eclips it wont let me get the day and the month from "dateOB" with this code.
could someone try and help me understand what is the problem !?

I suggest u to use a simple Bean ZodiacSign like that:
class ZodiacSign {
private String name;
private int startMonth;
private int startDay;
private int endMonth;
private int ednDay;
public ZodiacSign(String name, int startMonth, int startDay, int endMonth, int ednDay) {
super();
this.name = name;
this.startMonth = startMonth;
this.startDay = startDay;
this.endMonth = endMonth;
this.ednDay = ednDay;
}
// getter & setter
}
and iterate over a collection until you find a match, like this:
List<ZodiacSign> zodiac = Collections.emptyList();
zodiac.add(new ZodiacSign("AQUARIUS", Calendar.JANUARY, 20, Calendar.FEBRUARY, 18));
zodiac.add(new ZodiacSign("PISCES", Calendar.FEBRUARY, 19, Calendar.MARCH, 20));
// ..
zodiac.add(new ZodiacSign("CAPRICORN", Calendar.DECEMBER, 22, Calendar.JANUARY, 19));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
for (ZodiacSign sign : zodiac) {
if (month >= sign.getStartMonth() && month <= sign.getEndMonth()) {
if (dayOfMonth >= sign.getStartDay() && dayOfMonth <= sign.getEdnDay()) {
System.out.println("Zodiac Sign: " + sign.getName());
}
}
}

You can do it like this
public static void main(String[] args) throws ParseException {
Scanner userInput = new Scanner(System.in);
System.out.println("Hello you, Lets get to know each other");
String userName;
System.out.println("What is your name ?");
userName = userInput.nextLine();
System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
String dateOB = userInput.next();
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println(dateOB);
System.out.println("So your date of birth is " + dateOB);
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_YEAR);
// IF day is from January 20 - to February 18 this means he or she is aquarius
if (day >= 20 && day <= 49) {
System.out.println("Aquarius");
} else if (day >= 50 && day <= 79) {
//If day if from February 19 to March 20 then pisces
System.out.println("Pisces");
}
//write all zodiac signs ...
userInput.close();
}

I think you could get the day and the month of the user's input in "MMdd" format. Then use Integer.parseInt() to get a number, then use if statements to locate the zodiac sign since it is dependent on the day and the month.
For example Aries. Mar 21 - Apr 19. So you can get the input number from the user's date like:
int userVal=0;
if (userDate != null) {
DateFormat df = new SimpleDateFormat("MMdd");
userVal = Integer.parseInt(df.format(date));
}
Now you can return aries by doing:
if(userVal >= 321 && userVal <= 419) //Mar 21 == 0321 and April 19 == 0419
System.out.println("Your zodiac sign: Aries");
Just continue for the other signs.
Implementation
public static void main(String[] args) throws ParseException {
Date date;
int mmdd;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
DateFormat mmDDFormat = new SimpleDateFormat("MMdd");
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your date of birth(dd/MM/yyyy):");
String stringDate = scanner.next();
date = dateFormat.parse(stringDate);
System.out.println("This is your date of birth: " + dateFormat.format(date));
mmdd = Integer.parseInt(mmDDFormat.format(date));
System.out.println("This is the mmdd value: " + mmdd);
//Now getting the Zodiac sign
System.out.println("The zodiac sign of your date of birth is: ");
if (mmdd >= 321 && mmdd <= 419) {
System.out.println("ARIES");
} else if (mmdd >= 420 && mmdd <= 520) {
System.out.println("TAURUS");
} else if (mmdd >= 521 && mmdd <= 620) {
System.out.println("GEMINI");
} else if (mmdd >= 621 && mmdd <= 722) {
System.out.println("CANCER");
} else if (mmdd >= 723 && mmdd <= 822) {
System.out.println("LEO");
} else if (mmdd >= 823 && mmdd <= 922) {
System.out.println("VIRGO");
} else if (mmdd >= 923 && mmdd <= 1022) {
System.out.println("LIBRA");
} else if (mmdd >= 1023 && mmdd <= 1121) {
System.out.println("SCORPIO");
} else if (mmdd >= 1122 && mmdd <= 1221) {
System.out.println("SAGITTARIUS");
} else if ((mmdd >= 1222 && mmdd <= 1231) || (mmdd >= 11 && mmdd <= 119)) {
System.out.println("CAPRICORN");
} else if (mmdd >= 120 && mmdd <= 218) {
System.out.println("AQUARIUS");
} else if (mmdd >= 219 && mmdd <= 320) {
System.out.println("PISCES");
}
}
Nb: I used Netbeans 8.0.1

Well, finally i was able to get over the problem, with full understanding of new concepts thanks to #LordAnomander for his patience and detailed instructions, #cdaiga insightful alternative solutions and #Dato Mumladze cooperation.
the correct code i reached so far without the zodiac comparison which i will have to apply a switch method, and i am sure since i am still learning it will face some other issue but all good more to learn,
import java.util.*;
import java.text.*;
import java.lang.*;
public class signs {
public static void main(String[] args) throws ParseException {
Scanner userInput = new Scanner (System.in);
// Intro message
System.out.println("Hello you, Lets get to know each other");
// User input begin
//name
String userName;
System.out.println("What is your name ?");
userName = userInput.nextLine();
//date of birth
Date date = new Date();
String dateOB = "";
boolean correctFormat = false;
do{
System.out.println(" please enter you DoB (dd/MM/yyyy)");
dateOB = userInput.next();
try{
date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println("day and month " + dateOB);
correctFormat = true;
}catch(ParseException e){
correctFormat = false;
}
}while(!correctFormat);
//Choosing sign
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH)+ 1;
// announcing sign
//converting the day and month to a number to compare
int zodiacNum = day * 100 + month;
System.out.println(" zodiac number is " + zodiacNum);
//closing userInput
userInput.close();
}
}
Thank you again guys, i hope this could be helpful for someone with basic knowledge as mine, and help them understand some issues.

Once you have converted the input to a Date you can also get the information by using Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1;
Edit #1:
To get the number you want you have to do an additional calculation, i.e.,
int zodiacNumber = month * 100 + day;
It will result in 1105 for the input 05/11/1984. Vice versa you can use day * 100 + month if you prefer 511.
Or you can parse the date straight to the format you wish by using
int zodiac = Integer.valueOf(new SimpleDateFormat("ddMM").format(date))
which is an even shorter solution.
Edit #2: As you replied to one question with the comment you want a loop to make sure the date is entered in the correct format, do something like this:
boolean correctFormat = false;
do {
// ask the user for input
// read the input
try {
// try to format the input
correctFormat = true;
} catch (ParseException e) {
correctFormat = false;
}
} while (!correctFormat);
You can be sure the date was not entered in a correct way if the exception is thrown and thus, by setting the helper variable you can make sure to ask for a date until it is convertable and hence, correct.
Edit #3: You need to use a Date if you are working with SimpleDateFormat not a String.
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(dateOB));
will not work! You have to use
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date));
So your program has to look like this:
Date date = new Date();
String dateOb = "";
boolean correctFormat = false;
do {
(...)
date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
(...)
} while (...);
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date);
(...)
cal.setTime(date);
(...)
It is important for you to know that date is the real date whereas dateOB is only what the user entered - this String cannot be used as real date!

Related

Why doesn't my date validation code work?

my code doesn't return any value and i have no idea why. My assignment requires me to write a code that accepts date in mm/dd/yyyy format and im required to put leap year in. The problem is, i dont get back any input. Im an amateur ad i dont know what is wrong. Im also allowed to use Case statment but I'm not sure how to implement case.
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
if (month <= 0 || month>12)
{
System.out.println("invalid month ");
}
if (year%4 != 0 || month == 02 || day >= 29)
{
System.out.println("invalid date");
}
if (month == 4 || month == 6 || month == 9 || month == 11 || day >= 31)
{
System.out.println("Invalid day");
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || day >=32 )
{
System.out.println("Invalid day");
}
else
{
System.out.println("Valid date");
}
}
}
The code sets the delimiter to /. Then you enter something like 12/25/2016. The first sc.next() call gets the 12. The second one gets the 25. The third... waits, because it doesn't see another / so it doesn't know you're done. If you typed 12/25/2016/ with your current code, it would at least give output, even if that output isn't correct yet.
you want to use switch case then go through the below code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy/ format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
boolean valid = isValidDate(day,month,year);
if (valid == true)
{
System.out.println("Date is Valid");
}
else
{
System.out.println("Date is InValid");
}
}
public static boolean isValidDate(int day, int month ,int year)
{
boolean monthOk = (month >= 1) && (month <= 12);
boolean dayOk = (day >= 1) && (day <= daysInMonth(year, month));
return (monthOk && dayOk);
}
private static int daysInMonth(int year, int month) {
int daysInMonth;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10: // go through
case 12:
daysInMonth = 31;
break;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
// returns 30 even for nonexistant months
daysInMonth = 30;
}
return daysInMonth;
}
}
take input as 12/25/2016/, not this 12/25/2016.
Here is something to get you started:
final String DELIMITER = "/";
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a date in mm/dd/yyyy format:\n ");
String date = sc.next();
sc.close();
String[] dateParts = date.split(DELIMITER);
//check : if dateParts size is not 3 ....something is wrong
String mm = dateParts[0];
String dd = dateParts[1];
String yyyy = dateParts[2];
System.out.println(mm+" "+ dd +" "+ yyyy);
It seems you have put else in wrong place. Suppose you second condition is getting correct and all other false, then also your program will show it as valid date and same on the opposite side.
For example, say day is 30 for any date, then it will satisfy second condition and it will show you "Invalid date".
You should write if else as follows.
If{
If{
If{
}
}
}else{
}
All if must be in a nested if and then else. Your if else sequence is wrong.

Getting date from user (mm/dd/yyyy), checking to see if it is valid, printing date (month, day year)

I'm having a hard time with a few things. I'm fairly new to Java and I can't figure out how to read the first two digits to determine 08 or 09 due to the Octal digits. Also I'm getting a return of null, 1, 199 which don't need to be there. Help would be appreciated.
import java.util.*;
public class Dates {
public static void main(String[] args) {
String January,February, March, April, May, June, July,
August, September,October, November, December, month;
January = February = March = April = May = June = July =
August = September = October = November = December = month = null;
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter date in the format mm/dd/yyyy: ");
String input = myScanner.next();
String months = input.substring(0,1);
int monthInt = Integer.parseInt(months);
if (monthInt == 01){
month = January;
}
else if (monthInt == 02){
month = February;
}
else if (monthInt == 03){
month = March;
}
else if (monthInt == 04){
month = April;
}
else if (monthInt == 05){
month = May;
}
else if (monthInt == 06){
month = June;
}
else if (monthInt == 07){
month = July;
}
else if (monthDouble == 08){
month = August;
}
else if (monthDouble == 09){
month = September;
}
else if (monthInt == 10){
month = October;
}
else if (monthInt == 11){
month = November;
}
else if (monthInt == 12){
month = December;
}
else {
System.out.println("Invalid Month");
}
String days = input.substring(3,4);
int daysInt = Integer.parseInt(days);
if ((daysInt <= 31) && (monthInt == 1 || monthInt == 3 || monthInt ==
5 || monthInt == 7 || monthInt == 8 || monthInt == 10 || monthInt
== 12)){
daysInt = daysInt;
}
else if ((daysInt <= 30) && (monthInt == 4 || monthInt == 6 || monthInt
== 9 || monthInt == 11)){
daysInt = daysInt;
}
else if ((daysInt <= 28) && (monthInt == 2)){
daysInt = daysInt;
}
else
System.out.println("Invalid Day");
String year = input.substring(6,9);
int yearInt = Integer.parseInt(year);
if (yearInt >= 1900 && yearInt <= 2014) {
yearInt = yearInt;
}
else {
System.out.println("Year should be between 1900 and 2014");
}
String checkSlash = input.substring(2);
char slash = checkSlash.charAt(0);
if (slash == '/')
slash = slash;
else
System.out.println("Invalid format. Use mm/dd/yyyy");
System.out.println(month + " " + daysInt + ", " + year);
}
}
There are vastly better ways to do this, most notably using even Java's Date and SimpleDateFormat classes, but if you must know...
Don't include the leading zero on the integers. You're not going to be reading or otherwise dealing with octal values. January is the first month, and it's much more straightforward to represent it as 1.
I'll give you an alternative, if you really don't want to use SimpleDateFormat. Consider that we know the values all fall in an integral range (that is, they're all going to be less than 2.1 billion). If we let the Integer class do the work of parsing the value for us, then we can do this in much less code.
Further to that, we don't need to worry about weird substrings (which, by the way, yours will only grab the first element - which is problematic).
Let's use the String#split() method and break up the input string on forward slashes.
String[] brokenInput = input.split("/");
Now we're given by our format and convention that the month is in brokenInput[0], the day in brokenInput[1], and the year in brokenInput[2].
Parsing is easy then:
Integer monthInt = Integer.parseInt(brokenInput[0]);
Integer daysInt = Integer.parseInt(brokenInput[1]);
Integer yearInt = Integer.parseInt(brokenInput[2]);
try this for a simpler way
String strDate = "11/29/2009";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date dateStr = formatter.parse(strDate);
Java will consider numbers with leading zeros as octals, and a digit in octal base cannot be larger than 7. You will get an error if you try to use 08, 09. You could use Strings instead:
if (months.equals("01"))
...
And I think (since you want to compare with "01", "02", ...) you should use substring(0,2):
String months = input.substring(0,2);
I'm going to assume that there is a reason why you are doing this the long way.
To start with, removing the leading 0 of your int values when checking the month, they convert the value to octal, which you don't need...
if (monthInt == 1) {
month = January;
} else if (monthInt == 2) {
month = February;
} else if (monthInt == 3) {
month = March;
} else if (monthInt == 4) {
month = April;
} else if (monthInt == 5) {
month = May;
} else if (monthInt == 6) {
month = June;
} else if (monthInt == 7) {
month = July;
} else if (monthInt == 8) {
month = August;
} else if (monthInt == 9) {
month = September;
} else if (monthInt == 10) {
month = October;
} else if (monthInt == 11) {
month = November;
} else if (monthInt == 12) {
month = December;
} else {
System.out.println("Invalid Month");
}
This...
String months = input.substring(0, 1);
Will get the first character of the input, but you've asked the user for mm/dd/yyyy, which suggests that you want a two digit value for the month and day...besides, what happens if they type in 12?
Instead you could use String[] parts = input.split("/"); to split the input String on the / delimiter, this (if the input is valid) will give you three elements, one each part of the date value.
Then you can use...
int monthInt = Integer.parseInt(parts[0]);
//...
int daysInt = Integer.parseInt(parts[1]);
//...
int yearInt = Integer.parseInt(parts[2]);
To convert the individual elements.
This raises the question that you should probably validate the input value in some meaningful way BEFORE you try and split it.
The month values are all null
String January, February, March, April, May, June, July,
August, September, October, November, December, month;
January = February = March = April = May = June = July
= August = September = October = November = December = month = null;
Which basically means you output will always start with null. You actually need to assign these some meaningful value.
I'll also parrot what every body else has said, unless you have a really good reason to do otherwise, I'd be using Calendar and some kind of DateFormat to do all this...
Updated with a (slightly over the top) example
This basically takes your idea and use SimpleDateFormat and Calendar to perform the actual checking of the input, for example...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Date (mm/dd/yyyy):");
String input = kb.nextLine();
// This is a little excessive, but does a pre-check of the basic
// format of the date. It checks for a strict adhereance to
// the nn/nn/nnnn format. This might not be required as
// SimpleDateFormat can actually be configured to be lient in it's
// parsing of values
if (input.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
try {
// Parse the String input to a Date object
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date date = sdf.parse(input);
// Create a Calendar, going to use this to compare the resulting
// Date value, as the parser will auto correct the input
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Split the basic input along the / delimeter
String parts[] = input.split("/");
boolean valid = true;
// Check each part to make sure it matches the components of the date
if (Integer.parseInt(parts[0]) != cal.get(Calendar.MONTH) + 1) {
valid = false;
System.out.println(parts[0] + " is not a valid month");
}
if (Integer.parseInt(parts[1]) != cal.get(Calendar.DATE)) {
valid = false;
System.out.println(parts[1] + " is not a valid day of the month");
}
if (Integer.parseInt(parts[2]) != cal.get(Calendar.YEAR)) {
valid = false;
System.out.println(parts[2] + " is not a valid year");
}
if (valid) {
// Print the result...
System.out.println(new SimpleDateFormat("MMMM dd, yyyy").format(date));
}
} catch (ParseException ex) {
System.out.println("Unable to parse " + input + "; invalid format");
}
} else {
System.out.println("Invalid format");
}
}
}

Read and print out the dates in the format mm/dd/yyyy

I am really new to Java, and I am writing a Java program that reads dates in the format mm/dd/yyyy and prints out the date in the format day, year. The program must verify that the year is between 1900 and 2014 (both limits included) and that the day and month and year are valid and mutually consistent. If the input is incorrect, the program must display an appropriate message and terminate. If the input is correct, the output should be printed in the specified format.
For Example:
Enter Date
04/30/2013
April 30, 2013
Enter Date
01/12/1888
Year should be between 1900 and 2014
I am stuck at how to limit the year and days (like February only has 28), and how to print out like the examples above. I am suppose to use if else and switch statement for this problem. Here is the code i got so far, and thanks for your help.
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
int month, day, year;
Scanner input = new Scanner(System.in);
System.out.print("Please Enter Date in The Format mm/dd/yyyy : ");
month = input.nextInt();
day = input.nextInt();
year = input.nextInt();
String months = "January February March April May June July August "
+ "September October November December";
String January = months.substring(0,7);
String February = months.substring(8,16);
String March = months.substring(17,22);
String April = months.substring(23,28);
String May = months.substring(29,32);
String June = months.substring(33,37);
String July = months.substring(38,42);
String August = months.substring(43,49);
String September = months.substring(50,59);
String October = months.substring(60,67);
String November = months.substring(68,76);
String December = months.substring(77,85);
if (month == 1) {
months = January;
day = 31;
}
else if (month == 2) {
months = February;
day = 28;
}
else if (month == 3) {
months = March;
day = 31;
}
else if (month == 4) {
months = April;
day = 30;
}
else if (month == 5) {
months = May;
day = 31;
}
else if (month == 6) {
months = June;
day = 30;
}
else if (month == 7) {
months = July;
day = 31;
}
else if (month == 8) {
months = August;
day = 31;
}
else if (month == 9) {
months = September;
day = 30;
}
else if (month == 10) {
months = October;
day = 31;
}
else if (month == 11) {
months = November;
day = 30;
}
else if (month == 12) {
months = December;
day = 31;
}
else {
System.out.print("Invalid Month");
}
if (year >= 1900 || year <= 2014) {
System.out.print(year);
}
else {
System.out.println("Year should be between 1900 and 2014");
}
System.out.println(months + " " + day + ", " + year);
}
}
Use Calendar and SimpleDateFormat for working and formatting dates respectively in Java. That's the good choice! Please don't reinvent the wheel unless you are in your learning process.
Please read the documentation of Calendar and SimpleDateFormat API
You should use a SimpleDateFormat, and you can verify with a Calendar.
You should try using the classes Calendar, GregorianCalendar and SimpleDateFormat
You should use GregorianCalendar for formatting.
You have to skip the '/' character before reading another Integer.
/*month = input.nextInt();
day = input.nextInt();
year = input.nextInt();*/
String dummy = input.nextLine();
month = Integer.parseInt(dummy.substring(0, 2));
day = Integer.parseInt(dummy.substring(3, 5));
year = Integer.parseInt(dummy.substring(6, 10));
You last line is wrong
System.out.println(months + " " + day + ", " + year);
For Leap year stuff, you should visit the wiki.
http://en.wikipedia.org/wiki/Leap_year#Algorithm

How to write Java code to take any date user inputs, and list the next 40 days?

I am trying to ensure that my nextday method can add ONE day to the date the user entered and ensure it adds 40 days correctly, taking into account the correct days per month and leap years
public nextday() {
for (int count = 1; count < 40; count++)
;
}
public String toDayDateString() // toDayDateString method {
int countDays = 0;
for (int i = 1; i < getMonth(); i++) {
if (i == 2 && checkLeapYr(getYear()))
countDays += 29;
else
countDays += daysPerMonth[i];
}
countDays += date;
String message = String.format("\n", countDays, getYear());
return message;
}
private Boolean checkLeapYr(int inYear) { // check leap year method.
if (getYear() % 400 == 0 || (getYear() % 4 == 0 && getYear() % 100 != 0))
return true;
else
return false;
}
Below is a menu that is supposed to allow the user to choose to enter a date or quit, but the date is not being accepted correctly.
{
public static void main ( String [] args)
// User selects how they will enter the dates
{
+"(1) Enter the date as MM/DD/YYYY\n"
+"(Any Key) Quit\n";
int input=0;
Date newDate;
do{
String userInput = JOptionPane.showInputDialog(null, menu);
input = Integer.parseInt( userInput);
String outputMessage="";
if ( input = 1)
{
userInput =JOptionPane.showInputDialog(null, "Please enter a date as 02/28/2011");
switch ( input ) // here is where the menu choice will be evaluated
{
case 1 :
token = userInput.split("/");
if (token.length == 3 )
{
newDate = new Date( Integer.parseInt( token[0]),
Integer.parseInt( token[1]), Integer.parseInt( token[2]) );
outputMessage = newDate.toString();
JOptionPane.showMessageDialog(null, outputMessage);
}
break;
case 2:
} while ( input <>1); // this will quit the program when user selects any key other than 1 at the menu.
You should use java.text.DateFormat to parse date strings
Writing your own date arithmetic is very error prone (leap years are only one exception among many), better use a java.util.Calendar implementation instead.
As for the date arithmetic, here's how it's done with Calendar:
//TODO: parse input string with DateFormat
Date startDate = ... // your parsed date
Calendar cal = new GregorianCalendar();
cal.setTime(startDate);
for (int i = 0; i < 40; i++) {
// add a day
cal.add(Calendar.DATE, 1);
// and get the new result as date
Date date = cal.getTime();
System.out.println(date);
}
If you need to count backwards, add negative time amounts (days, hours etc).
public static void main(String[] args) throws IOException, ParseException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter date(dd/mm/yyyy) : ");
String input = br.readLine();
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Calendar cal = Calendar.getInstance();
Date date = df.parse(input);
cal.setTime(date);
cal.add(Calendar.MONTH, 1); // to get actual month,as it parses 02 as Jan.
for (int i = 1; i < 40; i++) {
System.out.println(" day " + i + " : " + cal.getTime());
cal.add(Calendar.DATE, 1);
}
}
public static void main(String[] args) throws IOException,ParseException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter date(dd/mm/yyyy) : ");
String input = br.readLine();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
Date date = df.parse(input);
cal.setTime(date);
for (int i = 1; i <=40; i++) {
cal.add(Calendar.DATE,1);
System.out.println(" day " + i + " : " + cal
.getTime());
}
}

Calculate current Age ; using Java

I am trying to calculate the current age of a user .. but using the format i would like to use has caused some issues for me .
I could just ask separately for the year , month and day but much rather prefer (mm/dd/yyyy)
//Need help turning (mm/dd/yyyy) that the user inputs into:
//yyyy;
//mm;
// dd;
package org.joda.time;
import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;
public class AgeCalculation{
public static void main(String[] args) throws IOException{
int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
Scanner myScanner = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Calendar cd = Calendar.getInstance();
try{
System.out.print("Enter your Date of Birth.(mm/dd/yyyy): ");
Dob = myScanner.nextLine() ;
// how to get year , month and date from (mm/dd/yyyy) format?
year = ;
if(year > cd.get(Calendar.YEAR)){
System.out.print("Invalid date of birth.");
System.exit(0);
}
month =
if(month < 1 || month > 12){
System.out.print("Please enter monthe between 1 to 12.");
System.exit(0);
}
else{
month--;
if(year == cd.get(Calendar.YEAR)){
if(month > cd.get(Calendar.MONTH)){
System.out.print("Invalid month!");
System.exit(0);
}
}
}
if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 ||
month == 9 || month == 11){
if(day > 31 || day < 1){
//leap year data below
System.out.print("Please enter day between 1 to 31.");
System.exit(0);
}
}
else if(month == 3 || month == 5 || month == 8 || month == 10){
if(day > 30 || day < 1){
System.out.print("Please enter day between 1 to 30.");
System.exit(0);
}
}
else{
if(new GregorianCalendar().isLeapYear(year)){
if(day < 1 || day > 29){
System.out.print("Please enter day between 1 to 29.");
System.exit(0);
}
}
else if(day < 1 || day > 28){
System.out.print("Please enter day between 1 to 28.");
System.exit(0);
}
}
if(year == cd.get(Calendar.YEAR)){
if(month == cd.get(Calendar.MONTH)){
if(day > cd.get(Calendar.DAY_OF_MONTH)){
System.out.print("Invalid date!");
System.exit(0);
}
}
}
}
catch(NumberFormatException ne){
System.out.print(ne.getMessage() + " is not a legal entry!");
System.out.print("Please enter number.");
System.exit(0);
}
Calendar bd = new GregorianCalendar(year, month, day);
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageYears--;
ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
if(day > cd.get(Calendar.DAY_OF_MONTH)){
ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
}
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else{
ageDays = 0;
}
}
else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
if(day > cd.get(Calendar.DAY_OF_MONTH))
ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else
ageDays = 0;
}
else{
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
ageMonths = 0;
ageDays = 0;
}
System.out.print("Age of the person : " + ageYears + " year, " + ageMonths +
" months and " + ageDays + " days.");
}
}
Here's a hint as how you could read in and parse the entered date:
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );
String dateLine = s.nextLine();
try
{
Date d = f.parse( dateLine );
System.out.println(d);
}
catch( ParseException e )
{
System.out.println("please enter a valid date in format mm/dd/yyyy");
}
That's just an example and should get you started with reading the date correctly.
For getting the years, days and months in between two dates I'd still recommend using JodaTime since that makes life much easier.
Using standard Java facilities, this could help you:
Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );
Note that you need to subtract the smaller date from the bigger, i.e. the difference must be positive (which should be true when subtracting birth dates from the current time).
This would give a difference of 0 years, 9 full months and 26 days between Jan 1st 2011 and Oct 26th 2011, and a difference of 21 years and 1 day (since we already started this day) between Oct 26th 1990 and Oct 26th 2011.
If you want to use JodaTime:
String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);
year = dateTimeOfBirth.getYear();
// Etc
try this, it out puts the age into a form field called age in a form called "form", assumes you called your textbox(where DOB is entered) "dob"
var d =document.getElementById('dob').value.split('/');
var today = new Date();
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))
{
t = age--;
}
else {
t = age
}
form.age.value = t;
}
You'll pobably need something like that:
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);

Categories