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);
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 :)
}
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 am trying to convert the String to java.sql.Date.
This string I am getting from my jsp page using request.getparameter(date); which will return string and now I am trying to convert this String to Java.util.Date and then converting to java.SQL.Date.
For this I am using the below code
DateFormat format=new SimpleDateFormat("MM-dd-yyyy");
java.util.Date parsed = new Date(0);
try {
System.out.println("inside try block");
format.setLenient(false);
parsed = format.parse(dob);
System.out.println("parsed date inside try block"+parsed);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But the statement parsed=format.parse(dob) is not executing.
Try the below code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Source
After the line parsed = format.parse(dob);
you have to add the below line to convert it to java.sql.date format.
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
If the string is like "12201430" then you have to use formatter like new SimpleDateFormat("MMyyyydd"),same way for other scenarios also else you will get a ParseException.
You can get this done by using this sample code
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
nowdate="12-30-2014"
Date YourResult=sdf.parse(nowdate);
java.sql.Date todayssqldate=new java.sql.Date(YourResult.getTime());
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 !!
I have a method which reads the date that in form of srring and then conver it format in dd-MM-yy and finally return a string as shown below..
public static String getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
DateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dfOut = new SimpleDateFormat("dd-MM-yy");
try {
Date date = dfIn.parse(dateString);
return dfOut.format(date);
} catch (ParseException e) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
}
now I am calling this method from somewhere as shown below....
String formatteddate = DateUtility.getSimpleDate11(settlementDate);
now please advise how can I change this in java.sql.Date as I want to store the date in java.sql.Date..
java.sql.Date sd ------ here i want tio store the date finally
folks ple\ase advise .
java.sql.Date takes long value in its constructor (irrespective of the date format)
Date date=dfIn.parse(dateString);
new java.sql.Date(date.getTime());
should be equivalent as they represent the same Date object.