Hi for some of the requirement i need to convert the string representation of date(with no format) to date object and convert back to string(with a specific format)
This is what i tried so far, the output is not coming as expected and it's printing something like 08140009 - Any idea what is this
And please provide any suggestions.
MY code is :
public String getDateBackToCST(String createDate){
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMddyyyy");
TimeZone obj = TimeZone.getTimeZone("CST");
dateFormatter.setTimeZone(obj);
Date createdDate = null;
try {
createdDate = dateFormatter.parse(createDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatter.format(createdDate);
}
You need to specific proper flags for SimpleDateFormat. You have 2 options to specify timezone z and Z and to specify day name use E like this
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws ParseException {
String date = "Sat Sep 20 23:39:04 IST 2014 ";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
System.out.println(sdf.parse(date));
}
}
Related
As the question title states, how would it be possible to check whether a String can be parsed by a SimpleDateFormat before doing so? For example consider the following:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatterTest {
DateFormatterTest() {
String[] dateStrings = new String[]{"Tue Jan 27 15:12:04 GMT 2015",
"",
"Wed Jan 28 15:02:04 GMT 2015"};
for(String dateString : dateStrings){
Date date = null;
try {
//check whether dateString is parsable
date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
java.lang.System.out.println(date + "");
}
}
public static void main(String[] args) {
new DateFormatterTest();
}
}
Would it be possible to check whether dateString is parsable, and if not leave the variable date as null? I know that I could just let the try...catch handle any parse exceptions. My other solution would be to write a regular expression to decide, but again I never quite trust that a regex will work in all cases.
The reason for this question is that I am reading in a large XML file using java DOM, and only some of the elements have an attached date attribute.
UPDATE: The reason that I am a little apprehensive about using the try catch to handle errors is the performance hit, as the XML file is rather large and it will be a common occurrence for the date variable to be missing. try..catchs are also bad for the readability of code.
You could use SimpleDateFormat.parse(String text, ParsePosition pos).
Like this:
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatterTest {
DateFormatterTest() {
String[] dateStrings = new String[]{"Tue Jan 27 15:12:04 GMT 2015",
"",
"Wed Jan 28 15:02:04 GMT 2015"};
for(String dateString : dateStrings){
Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(dateString, new ParsePosition(0));
java.lang.System.out.println(date + "");
}
}
public static void main(String[] args) {
new DateFormatterTest();
}
}
It returns null in case of error, as you want.
I agree with the comments that checking for the ParseException is a valid solution. You can simply extract this to a method and obtain the functionality you want. Here is an example using your code.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatterTest {
DateFormatterTest() {
String[] dateStrings = new String[]{"Tue Jan 27 15:12:04 GMT 2015",
"",
"Wed Jan 28 15:02:04 GMT 2015"};
for(String dateString : dateStrings){
Date date = null;
// call new method
date = parseDate(dateString);
java.lang.System.out.println(date + "");
}
}
private Date parseDate(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(dateString);
} catch (ParseException e) {
// ideally you would log this exception...
}
return date;
}
public static void main(String[] args) {
new DateFormatterTest();
}
}
I want to convert 3/13/2014 11:38:58 AM string to date format.
I see some examples but and also implement but I don't know how to convert AM/PM to 24 hour time format.
How to make it possible ?
Use SimpleDateFormat
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(string);
Using this you can convert your date and time..
SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
Date date_current = new Date();
Date date_start = null;
date_start = sdf.parse("3/13/2014 11:38:58 AM");
System.out.println("now time is.." + date_start);
Thanks..
Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}
i am getting my date input as a string in the format dd-mm-yy through jsp page. Because this format is better to understand . But now i want to store the date in yyyy-MM-dd HH:mm:ss format in my database. I am using the following code.
try
{
String s="30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
System.out.println(d1);
System.out.println(ft.format(d1));
} catch(Exception e) {
System.out.println("Exception:"+e);
}
My Jsp date format is dd-mm-yy, but it gives answer as
Tue Oct 04 00:00:00 IST 35
0035-10-04 00:00:00
what is my mistake?
can tell me anyone please
Thank you.
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
should be
d1=new SimpleDateFormat("dd-MM-yyyy").parse(s);
because the input date String you've provided String s="30-04-2013"; is of the format, dd-MM-yyyy. Hence, to parse this, you need to give dd-MM-yyyy format in your SDF.
Change the format in your code from yyyy-MM-dd to dd-MM-yyyy. A simple debug would have solved this issue.
i think you need to pass the Date object to format() method of SimpleDateFormat class instead of passing string to it
just try to do like as follows
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted_date = ft.format(new Date());
System.out.println(formatted_date);
let me know the status
happy coding
See below the working program. See the parse and format method.
import java.text.SimpleDateFormat;
public class DateParsing {
public static void main(String args[]) {
String s = "30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat nt = new SimpleDateFormat("yyyy-MM-dd");
try {
System.out.println(nt.format(ft.parse(s)));
}
catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
Here's the code that should work, but does not:
public static void main(String[] args) {
String datata = "23:00:01 GMT, Sun Jul 28, 2012";
String format = "HH:mm:ss zzz, EEE MMM dd, yyyy";
try {
DateFormat inputFormat = new SimpleDateFormat(format);
Date parsedDate = inputFormat.parse(datata);
System.out.println(parsedDate.toGMTString());
} catch (Exception e) {
e.printStackTrace();
}
}
I'm getting a parse exception. I triple checked the patterns, I even wrote it one beneath the other, and I still get an exception. Help, anyone?
It is probably because your default locale is not in english and the parser does not understand "Sun" and/or "Jul". Try using:
DateFormat inputFormat = new SimpleDateFormat(format, Locale.ENGLISH);
In my project I am using a date conversion as follows (I have taken only the relevant chunk for brevity)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class FormatTest {
public static void main(String[] args) {
try {
String destinationDateFormat = "MM/dd/yyyy HH:mm:ss";
String sourceDateFormat = "EEE MMM d HH:mm:ss z yyyy";
String dateString = "2011-12-20T00:00:00+00:00";
DatatypeFactory factory = DatatypeFactory.newInstance();
XMLGregorianCalendar cal = factory.newXMLGregorianCalendar(dateString);
Calendar gCal = cal.toGregorianCalendar();
Date convertedDate = gCal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(sourceDateFormat);
if (convertedDate != null) {
String convertedDateString = new SimpleDateFormat(destinationDateFormat).format(sdf.parse(
convertedDate.toString()).getTime());
System.out.println("Final Date :" + convertedDateString);
}
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
In my project the variables destinationDateFormat and sourceDateFormat is being read from a spring properties file. The above code works fine in the unix boxes where system locale is set as en_US or en_GB, but one of the test boxes has nl_NL locale and that's where the above code is failing giving a ParseException. The problem is like sourceDateFormat is not parse-able in nl_NL locale.
Can anybody suggest me what should be the corresponding sourceDateFormat in nl_NL locale?
I don't want to the change the java code as it is costly.
It looks like this might be it: EEEE, MMMM d, yyyy h:mm:ss a z
I wrote a small class to get it:
DateFormat f = getDateTimeInstance(FULL, FULL, new Locale("nl_NL"));
SimpleDateFormat sf = (SimpleDateFormat) f;
String p1 = sf.toPattern();
String p2 = sf.toLocalizedPattern();
System.out.println( p1 );
System.out.println( p2 );
Derived from this SO answer.
The date format symbols for en_US are:
GyMdkHmsSEDFwWahKzZ
The date format symbols for nl_NL are:
GyMdkHmsSEDFwWahKzZ
There is no difference. I got the date format symbols by executing the following Java lines:
System.out.println(DateFormatSymbols.getInstance
(new Locale("en_US")).getLocalPatternChars());
System.out.println(DateFormatSymbols.getInstance
(new Locale("nl_NL")).getLocalPatternChars());
I left the source date format the same:
String sourceDateFormat = "EEE MMM d HH:mm:ss z yyyy";
and modified your simple date format statement to this:
SimpleDateFormat sdf = new SimpleDateFormat(sourceDateFormat,
new Locale("nl_NL"));
With this simple date format change, your test code ran fine and produced the following results in the US Eastern time zone:
Date string: 2011-12-20T00:00:00+00:00
Final Date: 12/19/2011 19:00:00