Android parsing String to Date with SimpleDateFormat - java

I have String dateOrder= '2014-09-28' , i want to change format with SimpleDateFormat. but this is cannot formated.. how to solve ?
this my code
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
dateOrder = date.format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Try changing the first line to
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
You can use this for the parse. Then you need another SimpleDateFormat("dd/MM/yy") for formatting the new version.
The key point is that the parsing needs to be done with one pattern, and the formatting needs to be done with another. So rather than just creating one SimpleDateFormat instance, you need two, with different patterns: one for parsing, and one for formatting.

I believe you want something like this:
//first create an object that will parse your date as you have it ie 2014-09-28
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
//then use a different object to format the date as you want it ie 9/28/2014
dateOrder = new SimpleDateFormat("dd/MM/yy").format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Converting String to SQL 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());

SimpleDateFormat and Date Comparison not given correct ouput

try {
Date sysDate = new SimpleDateFormat("dd/mm/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/mm/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above is my following code snippet to check two dates which is greater or not.
When I am giving :
sysdate=12/9/2012 and userdate=11/9/2012 or 10/8/2012 or 15/9/2011 it is giving the correct output
But when I am giving :
sysdate=12/9/2012 and userdate=13/8/2012 or 15/7/2012 or 16/6/2012 it is giving incorrect output.
To my analysis I have come to this point if I choose any month between Jan' 12 to Aug '12 and select the day_of_month(i.e. 0,1,2,...,31) more than the current day_of_month (in this case 12), I always get an incorrect output.
Please suggest any possible solution.
The problem is the pattern which should be "dd/MM/yyyy" (with capital "MM" for month) instead of "dd/mm/yyyy" (with small "mm" which means minutes).
So, it should be as follows -
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date sysDate = df.parse(_sysDate);
Date userDate = df.parse(_userDate);
//...
try {
Date sysDate = new SimpleDateFormat("dd/MM/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/MM/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Date pattern is wrong dd/MM/yyyy instead of dd/mm/yyyy.
see this data format change like this dd/MM/yyyy in place of dd/mm/yyyy.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

parse string to date and time but not getting appropriate parsing

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.

Using SimpleDateFormat in a for loop on a list of objects

My app crashes whenever I try to do this:
for (CalendarEvent event : this.ListofEvents){
String myDate = new String(event.getDate());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
theDate = format.parse(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(theDate.getDate());
}
If I just print event.getDate() as a test, it displays all the dates. But when I try to format each date I'm assuming it locks up the phone resources. It's a fairly large List with many entries.
Perhaps there's a better method of getting the day, month, and year without taking up all the resources.
Why are you creating a DateFormat inside the loop? You create it, use it, and then it goes out of scope for GC in the next iteration.
Move it outside the loop:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
format.setLenient(false);
for (CalendarEvent event : this.ListofEvents){
// what does event.getDate() return? A java.util.Date? If yes, why are you doing this at all?
String myDate = new String(event.getDate());
try {
theDate = format.parse(myDate);
System.out.println(theDate.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
}

Android: I can't figure out SimpleDateFormat

I have tried and tried, but I cannot get my RSS app to properly format the pubDate into a more user friendly format.
String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
Date date = formatter.parse(str);
That code looks simple enough, but I get an unhandled type parse exception error on formatter.parse(str). Once that gets working, I then need to convert my RSS Pubdate to MM/dd.
The line of code to set the text for that is here:
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
Do I just change that to:
listPubdate.setText(date);
This looks so simple that it's driving me nuts that I can't find the answer.
you can get the date by this
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
and want to put in simple format then
String date=String.format(mDay+"/"+mMonth+"/"+mYear);
so you can use this very easily.
It sounds to me like you are actually running this and getting the error. As others have pointed out, the problem is you need to wrap the formatter.parse call in a try/catch block. This is a compilation problem, not a runtime problem.
The code you have will work as you expect once you fix this compile problem.
Use a second formatter to get the MM/dd output you want.
String str = "26/08/1994";
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
SimpleDateFormat outputFormatter = new SimpleDateFormat("MM/dd");
try {
Date date = inputFormatter.parse(str);
String text = outputFormatter.format(date);
listPubdate.setText(text);
} catch (ParseException e ) {
e.printStackTrace();
}
I get an unhandled type parse exception error on formatter.parse(str)
For that, you'll need to explicitly handle the exception, either by declaring that the currently executing method just throws it, or by catching it. For more information, I highly recommend going through the Exceptions Lesson in the Java Tutorial.
Here's an example of catching the exception.
String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //please notice the capital M
Date date;
try
{
date = formatter.parse(str);
}
catch (ParseException e)
{
// Handle error condition.
}
SimpleDateformat.parse(String) throws a checked exception... wrap it in a try/catch block.
Below is the sample code ... pay attention to format inside SimpleDateFormat Constructor. This string which to be parsed for date should be similar in format to that of string passed in SimpleDateFormat constructor
public Date getDate(String str) {
SimpleDateFormat sdFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss");
Date d = null;
try {
String str1 = str.substring(0, str.lastIndexOf(" ")).substring(0,
str.lastIndexOf(" "));
String str2 = str1.substring(0, str1.lastIndexOf(" "));
Log.v("str1", str2);
d = sdFormat.parse(str2);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}

Categories