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.
Related
I'm getting a parse exception when trying to run
SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.US);
String str = "11:22";
Date time = format.parse(str);
I haven't the foggiest what I'm doing wrong.
Try doing this bud and tell me whether it works for you or not!
Date dateInput;
String str = "11:22";
DateFormat inputFormat = new SimpleDateFormat("mm:ss");
try {
dateInput = inputFormat.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
Do you need the output too of the parsed date? If yes then tell me will update the answer. And if you still get the exception then try to print the log cat output which you'll find in this section.
Go below and check this out and copy paste the logcat.
If the beginning of the specified string cannot be parsed method parse which is of DateFormat class will generate ParseException.
So, We need to catch that exception. One of the method is given below in java code
import java.text.*;
import java.util.*;
public class Prg
{
public static void main(String args[]) throws Exception
{
SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.US);
String str = "11:22";
Date time = format.parse(str);
System.out.println(time.toString());
}
}
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;
}
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);
I'm running an application which gives me CSV logs as output. For the date field, it gives it to me in the following form:
"09/25/2012 08:47:46.983"
I want to read in the output data into a Java program, translating the output given and storing it as a long in my program. Does the DateFormat class or other similar class in Java allow me to specify a string in the above form? (I can write my own code to parse the above line, but I didn't want to make bad assumptions about the form of the incoming string.)
public class TestTest {
public TestTest() {
String dateString = "09/25/2012 08:47:46.983";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss.SSS");
try {
Date date = dateFormat.parse(dateString);
System.out.println("Date is: " + date.getTime());
} catch (ParseException ex) {
Logger.getLogger(TestTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
TestTest test = new TestTest();
}
}
i am attaching the code. In this code i am taking a string which is a date from a flat text file. It consist of AM/PM(12 Hour Format). When i am parsing it, it is not parsing well not parsing in 24 hour format. I want the time difference b/w the current time and the string from file. And because of AM/PM its not converting in 24 hour format. So its showing same time difference whether it is PM or AM. So tell me any fruitful suggestion if you have. I ll be really thankful to you guys.
public class Casting {
/**
* #param args
*/
static FileReader fw;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
fw = new FileReader("E://796F_log.txt");
BufferedReader pw =new BufferedReader(fw);
String last_Line_From_File="" ;
for (String message = pw.readLine(); message != null ; message = pw.readLine()) {
last_Line_From_File = message;
}
String[] array_Of_Data = last_Line_From_File.split("\\s") ;
String time = array_Of_Data[0]+" "+array_Of_Data[1]+" "+array_Of_Data[2] ;
System.out.println(time);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
Calendar cal = Calendar.getInstance();
String current_time = dateFormat.format(cal.getTime());
Date d1 = dateFormat.parse(time);
Date d2 = dateFormat.parse(current_time);
long total_time = d2.getTime()-d1.getTime();
total_time /= 1000 ;
System.out.println("current time "+d2.getHours()+":"+d2.getMinutes()+":"+d2.getSeconds()+"\n"+d1.getHours()+":"+d1.getMinutes()+":"+d1.getSeconds());
if(total_time <= 500)
{
System.out.println("working "+total_time);
}
else
System.out.println("nt working "+total_time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("did the smart thing or dumb thing");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("we did attempt closing");
}
}
}
}
The problem is your format:
"MM/dd/yyyy HH:mm:ss a"
The HH here means the 24-hour value. So it's expecting "19" for 7pm. It's almost always wrong to include both "HH" and "a" (the AM/PM designator) in the same format string.
You probably want either
"MM/dd/yyyy hh:mm:ss a"
or
"MM/dd/yyyy h:mm:ss a"
depending on whether you get things like "07:00:00 AM" or "7:00:00 AM".
If you're doing any significant amount of date/time work, I'd recommend using Joda Time instead of Date/Calendar, by the way.