I want to parse the date into a desired format but i am receiving an exception every time.
i know it is easy to implement but i am facing some problem don't know where exactly.:
Exception: java.text.ParseException: Unparseable date: "2014-06-04" (at offset 5)
Following is my code:
private String getconvertdate(String date) {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy",Locale.ENGLISH);
Date parsed = null;
try {
parsed = inputFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String outputText = outputFormat.format(parsed);
return outputText;
}
Input to method: 2014-06-04
Expected Output: 06-Jun-2014
I have followed some Ref. from Stackoverflow.com, but still he problem persist.
Please Help.
You have no time part in your string:
and the Month has only two character
replace
new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
with
new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
// Try this way,hope this will help you to solve your problem....
public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
try{
SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
return dateFormat2.format(sdf.parse(strDate));
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
Maybe you need to tackle different input formats
Then catch the currently unmanaged format exception (just a sample):
private String getconvertdate(String date) {
System.out.println(date.length());
DateFormat inputFormat = null;
if(date.length() == 20)
inputFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
if(date.length() == 10)
inputFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH) ;
if(null == inputFormat)
return "Format invalid";
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy",Locale.ENGLISH);
Date parsed = null;
try {
parsed = inputFormat.parse(date);
} catch (ParseException e) {
return "Input Date invalid";
}
String outputText = outputFormat.format(parsed);
return outputText;
}
In my case, I was using ::
SimpleDateFormat todaySdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
changed it to
SimpleDateFormat todaySdf = new SimpleDateFormat("dd MM yyyy", Locale.ENGLISH);
and it worked.. the extra M was the culprit !!
Related
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 :)
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format("2017-01-04"));
The above is my code and when I try to convert the date to gmt I get the error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date at
java.text.DateFormat.format(DateFormat.java:310) at
java.text.Format.format(Format.java:157) at
Sample.main(Sample.java:24)
Please point out what am I doing wrong.
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(new Date()));
This above code is working fine but I need something that works for any date.
And when I try this code:
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.parse("2017-01-04"));
} catch(Exception e) {
e.printStackTrace();
}
I am getting Unparseable date: "2017-01-04". Please tell me how to fix it
Try it..
String s = "2016-11-21 13:30:0.0";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss);
Date d = null;
try
{
d = format.parse(s);
} catch (ParseException e)
{
e.printStackTrace();
}
SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(gmtFormat.format(d));
When you have a date object then you can format it as you want:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
//create a calendar representing your date.
Calendar cal = Calendar.getInstance();
cal.set(2017, 01, 04);
//format the date object to the pattern you want.
String DateToStr = format.format(cal.getTime());
System.out.println(DateToStr);
If you have your date as string you can also do:
String string = "2017-01-04";
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
format1.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
try {
date = format1.parse(string);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(date);
The below code is to help in understanding better - you can try uncommenting the commented lines and compare the results. The point of interest for you in this whole block is gdf.parse(gmtFormat)
Date date = new Date();
DateFormat idf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
idf.setTimeZone(TimeZone.getTimeZone("IST"));
DateFormat gdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
gdf.setTimeZone(TimeZone.getTimeZone("GMT"));
//String istFormat = idf.format(date);
//System.out.println("IST: "+istFormat);
String gmtFormat = gdf.format(date);
System.out.println("GMT: "+ gmtFormat);
try {
//System.out.println("gmt parsed from istFormat: "+gdf.parse(istFormat));
//System.out.println("ist parsed from istFormat: "+idf.parse(istFormat));
System.out.println("gmt parsed from gmtFormat: "+gdf.parse(gmtFormat));
System.out.println("ist parsed from gmtFormat: "+idf.parse(gmtFormat));
} catch (ParseException e) {
e.printStackTrace();
}
I need help parsing this string of data and time. Could any one help me fix my format or give guidance? Thanks.
2016-04-23T01:00:00Z
SimpleDateFormat year = new SimpleDateFormat("mm:dd:yyyy");
SimpleDateFormat hour = new SimpleDateFormat("hh:mm:ss");
String yearParse = year.format(Date.parse(year));
String hourParse = hour.format(Date.parse(hour));
Use this methods to get Date and Time in format you wants
For Date
public static String getDate(String date) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = null;
try {
parsed = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
return formatter.format(parsed);
}
For Time
public static String getTime(String date) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = null;
try {
parsed = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(parsed);
}
Try
SimpleDateFormat sdf1= new SimpleDateFormat("mm-dd-yyyy");
SimpleDateFormat sdf2= new SimpleDateFormat("hh-mm-ss");
String year=sdf1.format(required_date);
String hour=sdf2.format(required_date);
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 have String variable which contains date. Now how to display July 15 from that string variable? (for example 2012-07-15)
String strdate = "2012-07-15";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd");
try {
d1 = formatter.parse(strdate);
System.out.println(d1 + "---date first---");
} catch (ParseException e) {
e.printStackTrace();
}
Your parsing template does not match your example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
(with MM instead of MMM).
To output July 15, you can use a second formatter:
SimpleDateFormat output = new SimpleDateFormat("MMMM dd");
System.out.println(output.format(d1)); //July 15
Something like,
try {
String strdate = "2012-07-15";
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"");
DateFormat df2 = new SimpleDateFormat("MMMM dd");
System.out.println(df2.format(df1.parse(strdate)+ "---date first---");
}
catch (ParseException e) {
// Exception handling
}