i get the single value from String array.this single value have zeroes.i want convert this zeroes to date and gettime...
String followupdate2="";
for(int i=1;i<2;i++){
followupdate2=followupdate1[i];
System.out.println("--------------"+followupdate2);
}
System.out.println("---------outer-----"+followupdate2);
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yy");
Date followupdate3=format1.parse(followupdate2);
long followupdate4=followupdate3.getTime();
followupdate2 have 00-000-00
i want convert followupdate2 to date ....
i want get long followupdate4=followupdate3.getTime();
error is:
java.text.ParseException: Unparseable date: "00-000-00"
at java.text.DateFormat.parse(Unknown Source)
You are feeding your program bad input. The output is TELLING YOU that you are feeding it bad input.
Use a try-catch block and deal with it.
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yy");
long followupdate4;
try {
Date followupdate3=format1.parse(followupdate2);
followupdate4 = followupdate3.getTime();
} catch (ParseException e) {
followupdate4 = 0; //Whatever you want here.
}
Related
This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?
The input parameter is: 03/01/18
Code to convert String to Date is given below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When tried to convert using this method it shows the following error
java.text.ParseException: Unparseable date: "03/01/18"
As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.
To Convert as Date,
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);
To Print it out in the other format,
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
You are writing it the wrong way. In fact, for the date you want to convert, you need to write
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.
You need to supply the correct format that you are passing your input as something like below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The solution for the above problem
Convert the String date value in the Format of "dd/mm/yy" to Date.
By using the converted Date can able to frame the required date format.
The method has given below
public static String stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
String dateString = null;
try {
// convert to Date Format From "dd/mm/yy" to Date
date = formatter.parse(dateVlaue);
// from the Converted date to the required format eg : "yyyy-MM-dd"
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
Oracle tutorial: Date Time explaining how to use java.time.
I need to convert timestamp string to long.
Here is my input string:
2016-08-10T11:24:57.182+0300
here is code witch I am trying to use for converting:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.sssZ");
try {
Date date = simpleDateFormat.parse(timestamp);
long time = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
result: 1470817622000
but when i check this long time here, it returns me this string:
10 august 2016 8:27:02 GMT
but this is different from the input string.
any idea why it happens and how to fix this?
How can one convert the input date formatted as mm/dd/yyyy into an integer formatted as yyyymmdd.
I tried:
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
t = ft.format(input);
and
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
try{
t = ft.parse(input);
}catch (ParseException e){
}
}
Neither of these worked; The first one gave me a runtime error.
Assuming the input date is in type of a String:
String strDate = "09/24/2015";
String[] tok = strDate.split("/");
System.out.println(tok[2] + tok[0] + tok[1]);
You can split them into tokens.
You can do it in two ways: String manipulation, or date parsing and reformatting.
// String substitution using regular expression
System.out.println("09/24/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
// Lenient date reformatting
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/24/2015")));
String substitution will do nothing for bad formats, and will convert good formats even if date values are bad.
The date reformatting will fail (exception) for bad formats, and will "adjust" bad date values (see below), because it's lenient by default. Change to strict to also fail on bad date values:
// Strict date reformatting
SimpleDateFormat mdy = new SimpleDateFormat("MM/dd/yyyy");
mdy.setLenient(false);
SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
System.out.println(ymd.format(mdy.parse("09/24/2015")));
The above three methods will all print:
20150924
To show the effect of bad date values,a dn with bad formats:
// Showing results with bad date
System.out.println("09/34/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/34/2015")));
try { ymd.format(mdy.parse("09/34/2015")); } catch (Exception e) { System.out.println(e); }
// Showing results with bad formats
System.out.println("Hello".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
try { new SimpleDateFormat("MM/dd/yyyy").parse("Hello"); } catch (Exception e) { System.out.println(e); }
try { ymd.format(mdy.parse("Hello")); } catch (Exception e) { System.out.println(e); }
Output
20150934
20151004
java.text.ParseException: Unparseable date: "09/34/2015"
Hello
java.text.ParseException: Unparseable date: "Hello"
java.text.ParseException: Unparseable date: "Hello"
How to differentiate between data-entry being (a) invalid date or (b) invalid format?
I have the following code for handling date inputs from an text file.
public boolean dateIsValid(String date) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
Date dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
I have everything working as I want it to. The only problem I have is I am unable to differentiate the different parse exceptions thrown. For example:
if String date = 18/10/2012 --> java.text.ParseException: Unparseable date: "18/10/2012"
if String date = 2-12-2001 --> java.text.ParseException: Unparseable date: "2-12-2001"
As you can see, both the wrong formats throw the same error. How can I differentiate them so that I can handle them differently?
EDIT
To be more precise, in case of date 18/10/2012, I should throw an invalid date error and in the case of date 2-12-2001, I need to throw an invalid format exception. I dont need to handle different formats. I just need a way of getting different exceptions for these two different cases.
The issue seems to be at this line
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
For the first error it looks like that the date is coming first and the month later so it should be like
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Second error shows the incorrect format of the date supplied since it is containing - whereas you are expecting the format containing / ie like
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you want to handle different formats then try like this:
String[] formatDates= {"MM/DD/yyyy", "dd/MM/yyyy", "MM-dd-yyyy","dd-MM-yyyy"};
Date tryParse(String dateString)
{
for (String formatDate: formatDates)
{
try
{
return new SimpleDateFormat(formatDate).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Unless you write code to parse the date strings yourself, you will not know why the format threw the exception.
I recommend a variation of the R. T. answer above.
Specifically, instead of creating a new formatter every time, create four (in that example) formatters at startup (in the constructor or in a static block).
I would use
public Date dateIfValid(String format, String date) {
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
return dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
return null;
}
}
Date mmddyy = dateIfavlid("MM/dd/yy", date.replace("[^0-9]", "/"));
Date ddmmyy = dateIfavlid("dd/MM/yy", date.replace("[^0-9]", "/"));
if (mmddyy != null && ddmmyy == null) {
Note: this can be used to detect ambigous dates such as 01/02/03 which might be 3rd Feb 2001
I am parsing multiple String objects containing date in format of mm/dd/yyyy into Date objects using SimpleDateFormatter
Problem I am facing is that, some String contain complete date means it is mm/dd/yyyy while some Strings do not contain year and comes in this format mm/dd
I am using this format to parse dates MM/dd/yyyy but everytime I get a String with only month and day, I get parsing exception.
I want to know, is there any way by which if a year field is missing then I can use something like 0000 or I need to tackle it into exception body only?
Just create 2 separate SimpleDateFormat instances, one that you have and a second one with day and month only. You analyze the string first and pass it to the correct formatter.
Or pass it to the first one and if an exception is thrown, pass it to the second one.
as far as i know you can create an instance of SimpleDateFormat that does not "need" an year.
So just use an try-catch-Block
try{
//try formatting with simpledate instance with year
}catch (Exception thrown when no year){
try{
//try formatting with simple date instace without year
} catch (Exception e)
//something went wrong both did not accept it
}
}
ParseDate(String yourDate);
{
try {
Date reqDate=sdf.parse(yourDate);//sdf is instance of you date formatter
return reqDate;
} catch (ParseException e) {
return null;
e.printStackTrace();
}
}
try Using this function. I think it will work. if thrown exception then null will return. In this way by checking null we know if it is correctly parsed or not.
A code is worth thousand words....
DateFormat df;
Calendar c = Calendar.getInstance();
String s = new String("12/25/2012");
String[] arr = s.split("/");
if(arr.length>2){
c.set(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]),Integer.parseInt(arr[2]));
}
else{
c.set(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]));
}
df = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println(df.format(c.getTime()));
You can later convert it back to Date object using the df.parse() method...