unexpected output while converting a string to date in java - java

I have a string "12/9/2010 4:39:38 PM" which i have to convert to a date object. I am using the following code to do it:
String str = "12/9/2010 4:39:38 PM";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("M/dd/yyyy H:m:s a");
date =(Date)formatter.parse(str);
System.out.println("date printed"+date);
However, when im printing the output, i see
Thu Dec 09 04:39:38 IST 2010
How do I get the date exactly the way I declared in the string i.e
12/9/2010 4:39:38 PM
as output? Pls help

You're assuming that the Date value itself remembers the format - it doesn't. Date.toString will do what it wants - because the Date only represents an instant in time.
If you want to format a Date, use your formatter again:
System.out.println(formatter.format(date));
However, that won't necessarily return the exact same value that was in your string, as there may be multiple values which parse the same way. For example, as you've only used "H:m:s", I'd expect "4:5:6" to be parsed the same way as "04:05:06".

You can entirely specify the format of your date output using the class Formatter
Short answer
String str = "12/9/2010 4:39:38 PM";
Formatter formatter = new SimpleDateFormat("M/dd/yyyy H:m:s a");
Date date =(Date)formatter.parse(str);
Formatter formatterOutput = new SimpleDateFormat("MM/dd/yyyy HH:m:ss a");
String s = formatterOutput.format(date);
Other examples
Format formatter;
// The year
formatter = new SimpleDateFormat("yy"); // 02
formatter = new SimpleDateFormat("yyyy"); // 2002
// The month
formatter = new SimpleDateFormat("M"); // 1
formatter = new SimpleDateFormat("MM"); // 01
formatter = new SimpleDateFormat("MMM"); // Jan
formatter = new SimpleDateFormat("MMMM"); // January
// The day
formatter = new SimpleDateFormat("d"); // 9
formatter = new SimpleDateFormat("dd"); // 09
// The day in week
formatter = new SimpleDateFormat("E"); // Wed
formatter = new SimpleDateFormat("EEEE"); // Wednesday
// Get today's date
Date date = new Date();
// Some examples
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
// 01/09/02
formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);
// 29-Jan-02
// Examples with date and time; see also
// Formatting the Time Using a Custom Format
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date);
// 2002.01.29.08.36.33
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500
from: http://www.exampledepot.com/egs/java.text/formatdate.html

Use the same formatter:
System.out.println("date printed "+ formatter.format(date));

Converting it back to String using SimpleDateFormat?

formatter = new SimpleDateFormat("MM/dd/yyyy HH:m:ss a");
String temp =formatter.format(date );

Java.util.Date has no concept of an intrinsic format - You need to use the format(java.util.Date d) method to see a formatted String representation of your Date object.
String str = "12/9/2010 4:39:38 PM";
DateFormat formatter = new SimpleDateFormat("M/dd/yyyy H:m:s a");
Date date =(Date)formatter.parse(str);
System.out.println("date printed"+formatter.format(date));

Not sure what you are trying to accomplish. But you'll have to call SimpleDateFormat.format() to get what you are expecting. Printing the date directly will get only toString() implementation of Date

public static void main(String args[])
{
String string="2012-09-13";
Date str=processFileDate(string);
System.out.println(str);
}
public static Date processFileDate(String str)
{ //returns the date or "null" if doesn't exist
String[] strformat={
"EEE,dd MMM yyyy","MMM dd, yyyy, hh.mmaa zzz",
"EEEE, MMMMM dd yyyy 'at' hh:mm",
"EEEE, MMMMM dd, yyyy, hh:mm",
"EEE MMM dd yyyy, hh:mm ",
"dd MMMMM yyyy'Last updated at' hh:mm zzz",
"MMM dd, yyyy 'at' hh:mmaa",
"MMM dd, yyyy 'at' hh:mmaa zzz",
"MMMMM dd, yyyy, hh:mm aa zzz",
"EEE, MMM dd, yyyy hh:mm ",
"MMMMM dd, yyyy hh:mm zzz",
"MMMM dd, yyyy hh:mm aa",
"MMMM dd, yyyy hh:mmaa",
"MMMM dd, yyyy hh:mm",
"dd MMMM yyyy hh:mm:ss",
"dd MMMM yyyy hh:mm",
"MMMM dd, yyyy",
"dd MMMM yyyy ",
"dd MM yy",
"yyyy MMMM dd",
"dd'st' MMMM,yyyy",
"dd'nd' MMMM,yyyy",
"dd'rd' MMMM,yyyy",
"MMMM dd,yyyy",
"MMM dd yy",
"mm dd yy",
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss",
"E MMM dd hh:mm:ss Z yyyy",
"EEE, dd MMM yyyy HH:mm:ss Z"
};
String temp="null";
for(int i=0;i<str.length();i++){
temp=str.substring(i, str.length());
for(int l=0;l<strformat.length;){
Date strp=checkformat(temp,strformat[l]);
if(strp!=null)
{
return strp;
}
else l++;
}
}
return null;
}
private static Date checkformat(String str, String sdf) {
SimpleDateFormat sdformat=new SimpleDateFormat(sdf);
try{
Date d=sdformat.parse(str);
return d;
}catch(Exception e){}
return null;
}

Related

how to convert GMT to Local date time in android

I have a time like this : Thu, 27 Oct 2016 18:17:47 GMT
I have tried the code bellow but didn't work
String inputText = "Thu, 27 Oct 2016 18:17:47 GMT";
SimpleDateFormat inputFormat = new SimpleDateFormat
("EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
SimpleDateFormat outputFormat =
new SimpleDateFormat("MMM dd, yyyy h:mm a");
// Adjust locale and zone appropriately
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);
System.out.println(outputText);
Your input date and input format don't match each other. Try this input format instead:
SimpleDateFormat inputFormat = new SimpleDateFormat
("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
Here are a couple of functions that will do it:
public static Date toLocale(Date date) {
int GMTOffset = (int) TimeUnit.HOURS.convert(calendar.getTimeZone().getRawOffset(),
TimeUnit.MILLISECONDS);
return addHours(date, GMTOffset);
}
public static Date addHours(Date date, int hours) {
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();
}

Date format in java

Am getting response as
"pickTime": "Tue Oct 25 03:57 PM"
i had coded as follows to get.
SimpleDateFormat curFormater = new SimpleDateFormat("E MMM dd hh:mm a");
SimpleDateFormat dateFormater = new SimpleDateFormat("E MMM dd");
SimpleDateFormat timeFormater = new SimpleDateFormat("hh:mm a");
String time = jsonObj.optString("pickTime");
Date dateObj = curFormater.parse(time);
String newDateStr = dateFormater.format(dateObj);
String newTimeStr = timeFormater.format(dateObj);
The problem is I am getting same value in String time but in dateobj I am getting value as
"sun oct 25 15.57 pm"
newDatestr as
"sun oct 25"
Please help me to solve this problem ,thanks in advance
It is taking the October 25 of 1970 (Linux time).
You have to figure out how to add the year to the date because it is not taking the current year.
It takes the default one instead (the linux time starts on January 1 1970).
Your response does not contains year. So you are getting incorrect output.
Below code is working try it out.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
SimpleDateFormat curFormater = new SimpleDateFormat("E MMM dd hh:mm a yyyy");
SimpleDateFormat dateFormater = new SimpleDateFormat("E MMM dd");
SimpleDateFormat timeFormater = new SimpleDateFormat("hh:mm a");
String time = "Tue Oct 25 03:57 PM" + " " + calendar.get(Calendar.YEAR);
Date dateObj = null;
try {
dateObj = curFormater.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Logger.logd(this, dateObj.toString());
String newDateStr = dateFormater.format(dateObj);
String newTimeStr = timeFormater.format(dateObj);
Logger.logd(this, newDateStr + " " + newTimeStr);
SimpleDateFormat formatter =new SimpleDateFormat("EEE MMM dd hh:mm a");
Date date2 = formatter.parse("Tue Oct 25 03:57 PM");
long time = date2.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
cal.set(Calendar.YEAR, 2016);
String formatted = formatter.format(cal.getTime());
System.out.println(formatted);
#David Marciel is right. you should specify year.
SimpleDateFormat curFormater = new SimpleDateFormat("E MMM dd hh:mm a");
in this why you have put E.
SimpleDateFormat curFormater = new SimpleDateFormat("EEE MM dd yyyy hh:mm a");
I think this should be format.

"Unparsable date" when trying to reformat a date String

I want to reformat a given date String into a different format:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy 'at' KK:mm aa zzzz");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = simpleDateFormat.parse(question.getOccur());
String formattedTime = output.format(d);
I'm getting this exception:
java.text.ParseException: Unparseable date: "Monday, December 7, 2015 at 12:05:13 PM Eastern Standard Time" (at offset 33)
You missed the seconds from your date format.
Try this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy 'at' KK:mm:ss aa zzzz");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = simpleDateFormat.parse(question.getOccur());
String formattedTime = output.format(d);
Edit. For the following example: Thursday 12/10/2015 01:35 AM, the date format is this:
SimpleDateFormat output = new SimpleDateFormat("EEEE dd/MM/yyyy hh:mm a");

Getting the month and day from a TimeStamp

I have a String timeStamp in this format "Wed, 29 Jan 2014 20:14:15 GMT". I want to be able to compare this date with another date that is in this format 01/25/1999. I have tried simpledateformatter but with no success.
String a = connection.getHeaderField("Last-Modified"); //Returns Wed, 29 Jan 2014 20:14:15 GMT
Date lastModDate = new Date(file.lastModified()); //returns 01/25/1999
This is the simpleDateFormatter I tried implementing
SimpleDateFormat formatter;
Date dateIn = null;
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
try{
dateIn = (Date)formatter.parse(a);
}catch(ParseException e){
e.printStackTrace();
}
Log.d(TAG, "The server date is formated to : " + dateIn);
The dateIn is always null.
I want the to be able to do something like this
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
}
Use the following code...you will get the problem right.
Calendar calender = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String timeStamp = formatter.format(calender.getTime());
Date strDate = formatter.parse(timeStamp);
String currentTimeStamp = formatter.format(new Date());
Date currentTime = formatter.parse(currentTimeStamp);
if (currentTime.after(strDate)) {
}
Don't know what you tried but this should work:
String a = connection.getHeaderField("Last-Modified");
Date date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).parse(a);
This can help http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The reason is that you are using the wrong date format for your formatter. If the date you receive looks like
"Wed, 29 Jan 2014 20:14:15 GMT"
Then you should use the following format
formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
You should use the Calendar class and its subclass GregorianCalendar. For exampe, to get the month of your date:
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.get(Calendar.MONTH);

How to parse date to EEE MMM dd HH:mm:ss zzz yyyy format?

I am getting date from database as 2013-05-03 00:20:29.0. I want to parse the date to EEE MMM dd HH:mm:ss zzz yyyy format, but when I am parsing it, I am getting this exception:
java.text.ParseException: Unparseable date: "2013-05-03 00:20:29.0"
My code is below:
String createdDate = "2013-05-03 00:20:29.0";
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date parseDate = format.parse(createdDate);
You have to adjust the Format pattern. Format must be yyyy-MM-dd HH:mm:ss.S
Try this
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your SimpleDateFormat pattern does not match createdDate. The format should be:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
See the javadoc
As I understod you want to convert your date to a new format
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse("2013-05-03 00:20:29.0");
String str = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(date);
You can also try to get the date from the DB not as String but as java.sql.Date then the first step will be unnecessary
Here is an example:
String str_date= "29/02/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dt = sdf.parse(str_date);
DateFormat df = new SimpleDateFormat("EEEE");
System.out.println(df.format(dt));

Categories