Date Formatting using SimpleDateFormat - java

Here the user need to enter the Name, Date of Birth and Date of joining. The program need to check whether the entered date is valid with any of the given 3 formats dd/MM/yyyy , dd-MMM-yyyy and dd MMMM yyyy. If invalid, user need to re-enter. Finally i want to print back an auto-increment ID,Name,Date of Birth and Date of Joining back. Can you help me with the program. I cannot find any solution for exception handling.
public class EmployeeInfo {
int id;
static String name, DoBS, DoJS;
Date DoB, DoJ;
public void checkDate(String dt) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");
Date date = null;
if (date == sdf1.parse(dt))
try {
date = sdf1.parse(dt);
}
catch (ParseException e) {
e.printStackTrace();
DoB=date;
}
else if (date == sdf2.parse(dt))
try {
System.out.println("hsd");
date = sdf2.parse(dt);
}
catch (ParseException e) {
e.printStackTrace();
}
else if(date==sdf3.parse(dt))
{
try{
date=sdf3.parse(dt);
}
catch(ParseException e){
e.printStackTrace();
}
}
{
void print() {
System.out.println("User ID: " + id);
System.out.println("Name: " + name);
System.out.println("Date Of Birth: " + DoB);
System.out.println("Date of Joining: " + DoJ);
}
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name: ");
name = scanner.nextLine();
System.out.println("Enter the Date Of Birth: ");
DoBS = scanner.nextLine();
System.out.println("Enter the Date of Joining: ");
DoJS = scanner.nextLine();
EmployeeInfo e = new EmployeeInfo();
e.checkDate(DoBS);
e.print();
}
}

As for the actual checking of dates, if you only want to support those three date formats you could simply use three nested try catch statements. Something like this:
try {
date = sdf1.parse(dt);
} catch (ParseException e) {
try {
date = sdf2.parse(dt);
} catch (ParseException e1) {
try {
date = sdf3.parse(dt);
} catch (ParseException e2) {
// TODO: Whatever to do when it doesn't find a date
}
}
}
If you want a more dynamic approach you could put the SimpleDateFormat objects in an array and use a loop with a try-catch inside.
EDIT:
Alright, what you want to do is make the checkDate method return a Date object. If it can't parse a date in your three formats, either return null or throw an exception. When entering the dates, you want to have a while loop checking whether or not the date is valid, using the checkDate method, and make the user reenter if it's invalid.
A few notes about your code:
In Java, fields of classes are usually private, with getter and setter methods to control them - this is called encapsulation.
Static fields are meant for variables that are the same across all of your instances. Name and dates specific to one EmployeeInfo object should not be static. You should create an EmployeeInfo object and then set the respective values of the object.
It is also common practice to have all your methods be either private or public (or protected in the case of inheritance) depending on their intended usage.
I suggest you read up a little on the basics of OOP in Java.

You asked several things in your question but regarding the date-paersing issue, you could implement it like following :
private static final List<DateFormat> ORDERED_FORMATS = Arrays.asList(new SimpleDateFormat("dd/MM/yyyy"),new SimpleDateFormat("dd-MMM-yyyy"),new SimpleDateFormat("dd MMM yyyy"));
public static Date parseDate(String date) {
for(DateFormat format : ORDERED_FORMATS){
Date result = tryParse(date, format);
if(result != null){
return result;
}
}
throw new IllegalArgumentException("Could not parse "+date);
}
private static Date tryParse(String date, DateFormat format){
try{
return format.parse(date);
} catch (ParseException e) {
System.out.println("Too bad : "+e.getMessage());
}
return null;
}

Related

Calculating the age of two LocalDates

Code:
public String Calcage(){
int age = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date birth = sdf.parse(dateOfBirth);
Date d = new Date();
LocalDate birthday = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
age = Period.between(birthday, now).getYears();
} catch (ParseException e) {
e.printStackTrace();
}
return String.valueOf(age);
}
PROBLEM: It returns zero every time. The Date which I use for testing is 1985-01-07
If you are actually using 1985-01-07 it correctly returns 0 and should also throw a ParseException which will be caught from the catch block and the stacktrace will be printed.
Your code should work for 07.01.1985 and return 35.
if you want nevertheless to use 1985-01-07 you should edit the specified format to "yyyy-dd-MM" or "yyyy-MM-dd"

Java - How to check if a value is of type Date

I have a project requirement. There are values in a .txt as -
02/01/2017 00:00:00
Now I need to have some rules to check if this value in the data file is of type Date. How can I do that? Thanks. I am new to Java so any help much appreciated. Thanks
Try to parse it to date. If it throws ParseException then it is not a date.
String dateString = "02/01/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date date;
try {
date = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
If you just want valid days, use non-lenient parsing:
String dateString = "02/28/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setLenient(false);
Date date;
try {
date = df.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
This will throw an exception for non-existing days like the 31st of February
Methord 1
Date dt = new Date(); //this should your Dynamic object
if (dt.getClass().equals(new Date().getClass()))
{
//if its date object
}
Methord 2
if(dt instanceof Date){
//if its date object
}
Use this to check date
String sDate1="31/12/1998 00:00:00";
try{
Date date1=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse(sDate1); `
}
catch(Exception e)
{
//Not a date..
}
You can use regular expressions to check the format
public boolean isDate(String s){
String pattern= "([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})";
return s.matches(pattern);}
Here’s the Java 8 solution (it can be made to work in Java 6 and 7 too when you use the ThreeTen Backport).
private static final DateTimeFormatter DATE_TIME_FORMAT
= DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")
.withResolverStyle(ResolverStyle.STRICT);
public static boolean hasTypeDate(String stringFromTxt) {
try {
DATE_TIME_FORMAT.parse(stringFromTxt);
return true;
} catch (DateTimeParseException dtpe) {
return false;
}
}
Stay away from SimpleDateFormat for new code. It has had its time, it’s been outdated for a while now.
If you intended the day of month first (if 02/01/2017 means January 2nd), you need the format pattern dd/MM/uuuu HH:mm:ss instead.
If you need to know which date and time was in the .txt, use:
LocalDateTime dateTime = LocalDateTime.parse(stringFromTxt, DATE_TIME_FORMAT);
Link: ThreeTen Backport: java.time classes for Java 6 and 7.
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
isValidDate(line));
//do what you want :)
}

How to convert a Date got at runtime from user in String format into Date format to feed it in the database

public Date getTransactionDate()
{
System.out.println("Enter the transaction Date");
String date = sc.next();
DateFormat df = DateFormat.getDateInstance();
String s1 = df.format(date);
Date d1 = null;
try
{
d1 = (Date) df.parse(s1);
} catch (java.text.ParseException e)
{
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
return d1;
}
Date d2 = new PreparedStmnt().getTransactionDate();
public static void addTransaction(Connection connection, PreparedStatement preparedStatement , long transac_Id , Date transac_date)
throws SQLException
{
String sqlQuery = "INSERT INTO TRANSACTIONS VALUES (?,?)";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setLong(1, transac_Id);
preparedStatement.setDate(2, transac_date);
preparedStatement.executeUpdate();
}
Its a Simple Transaction entry where i want the user to provide date at runtime and then store that in the database.But while doing so, I'm getting a bug saying:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at bluePrint.PreparedStmnt.getTransactionDate(PreparedStmnt.java:76)
at bluePrint.PreparedStmnt.main(PreparedStmnt.java:30)
Well this is my first project m working on. So, please help me.
you should use sc.nextLine() Instead sc.next() because its not consider space
you can try like
System.out.println("Enter the transaction Date");
String string = "January 2, 2010";
Scanner sc = new Scanner(System.in);
string = sc.nextLine();
System.out.println(string);
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
try {
Date date = format.parse(string);
System.out.println(date);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
this worked for me. entered date format January 2, 2010

parsing only the Year in a DateFormat Java

I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
//if(s.matches(""))
format = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?
I'd try:
public Date stringToDateReport(String s){
DateFormat format;
Date date = null;
format = new SimpleDateFormat("dd-MM-yyyy");
if(s.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
//you should do a real logging here
e.printStackTrace();
}
return date;
}
The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.
Try this code
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
if(s.indexOf("-") < 0){
format = new SimpleDateFormat("yyyy");
}else{
format = new SimpleDateFormat("dd-MMM-yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is there the possibility in have another format in the String s ? Or just these two?
public Date stringToDateReport(String strDate){
DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if(strDate.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(strDate);
} catch (ParseException e) {
//error parsing date
e.printStackTrace();
}
return date;
}
then call it like this :
String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);

Simple time parsing of a String

In the below code i need to get a parse exception.but the program somehow converts it to a valid date.
But if i give dthours as "07:0567" it is giving parse error.So how to keep the exact format shown.
Can anyone tell me what to do to throw an error if the date string deviates from the given format ("HH:MM:SS") even by a single character.
public static void main(String[] args) {
String dthours="07:4856:35563333";
SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
try
{
Date d = df.parse(dthours);
System.out.println("d "+d);
}
catch (ParseException e)
{
System.out.println("parseError");
}
Set the df.setLenient() to false so that the SimpleDateFormat will throw parse exception in such cases.
public static void main(String[] args)
{
String dthours = "07:4856:35563333";
SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
df.setLenient(false);
try
{
Date d = df.parse(dthours);
System.out.println("d = " + d);
}
catch (ParseException e)
{
System.out.println("parseError");
}
}
The above snippet would print "parseError" for that input.

Categories