Date converter in JAVA [duplicate] - java

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.

Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.

As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.

One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}

Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));

If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy

Related

How to convert date strings from different TimeZones to Date object in one TimeZone

Im working on an RSS reader software. I get items with their pubDate (publish date) values as string, convert them to Date object, and put them to my DB. However, when I check my DB, I saw some interesting values such as the date of tomorrow.
I research this situation and found that it is about time zone value Z. For example when I get "Mon, 26 May 2014 21:24:29 -0500", it becomes "2014-05-27 05:24:29", the next day !
All I want is to get dates in any timezone and convert them to date in common timezone, such as my country's.
Here is my code :
public static String convert(String datestr) throws ParseException {
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return resultFormatter.format(date);
}
And I use the method like that :
System.out.println(convert("Mon, 26 May 2014 21:24:29 -0500"));
The output is : 2014-05-27 05:24:29
Any idea ?
Since you haven't set a time zone, it's using your system's default.
Set a specific IANA time zone.
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
resultFormatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
return resultFormatter.format(date);
Looks like you passed a Date with timezone, but given a wrong format. If you are passing timezone like "-0500" you should rather use:
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
Remember that the system will always display the date using the current, default timezone (TimeZone.getDefault()) unless you override it by:
resultFormatter.setTimeZone(...)
This is working as expected. The date is converted as per your system's timezone.
Check the UTC offset of your system and replace it in the sample date string and look at the output.
For e.g: India is UTC+5:30
String datestr="Mon, 26 May 2014 21:24:29 +0530";
output:
2014-05-26 21:24:29
Alternate solution
If you don't want to consider the timezone of the input date string then simply truncate this information and remove zzz from pattern as well as shown in below code:
String datestr = "Mon, 26 May 2014 21:24:29 -0530";
datestr = datestr.replaceAll("\\s[-+](\\d+)$", ""); // truncate the timezone info if not needed
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); // remove zzz from the pattern
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(resultFormatter.format(date));

SimpleDateFormat parsing date string incorrectly

I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.
My date formatting code is as follows:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.
Any help is much appreciated.
You are parsing days 31 as months. SimpleDateFormat tries to give you a valid date. Therefore It adds to 1/0/2013 31 months. This is 2 years and 7 month. So you get your result 01/07/2015. So SimpleDateFormat works correct.
One solution for you is to change your date pattern to M/d/yyyy h:m:s a or your input data.
To avoid these tries you have to switch off SimpleDateFormat lenient mode. Then you will get an exception if the format does not fit.
It looks like your input format is actually months first, then days. So should be "MM/dd/yyyy".
So:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
Another example like this
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));
Output is: 2019-05-29
I expect to throw parse exception but not (41)is not a valid month value.
on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.

getting the wrong timezone in java / android [duplicate]

This question already has answers here:
Is java.util.Date using TimeZone?
(5 answers)
Closed 7 years ago.
String = 26/8/2013 15:59;
I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());
Output :
Mon Aug 26 18:59:00 EEST 2013
Whats wrong ?
Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:
final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);
// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59
Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.
When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.
If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.
I think you should use the below approach:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);

Set a String variable to a Date object in java

I want to set a hand written String as the date for a Date object. What I'm trying to say is that I want to do is this:
String date= [date string here!!!];
Date mydate = new Date(date);
Something like that. The reason I want to do this is because I want my network to have standard Date and Time because since I run them from the same machine the time is being taken from the same clock and it gets different time every time. So I want to get that time and also add 1-2 seconds in the end so I can test my nodes with different times.
Java is strongly typed language. You cannot assign string to Date. However you can (and should) parse string into date. For example you can use SimpleDateFormat class like the following:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse("2013-05-06");
you'll want to use dateformatter
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = formatter.parse("01/29/02");
String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010
updated
String string ="2013-04-26 08:34:55.705"
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(string);
System.out.println(date);

Parsing date from Calendar in Java

I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.

Categories

Resources