How to parse date string using Timezone in GWT - java

Has anybody succeeded parsing date string with a custom timezone in GWT? GWT's DateTimeFormat allows to format dates based on time zone, but I haven't found any method for doing opposite operation. So what should I do if I have following string "02:01:2011" (format "MM:dd:yyyy"). It can have different results in different timezones.
The other problem appears when trying to change dates, months and etc. How can I do it based on a custom timezone?
Maybe there is any library which can simplify all these operations?
I have made workaround and add timezone part to each date string which miss that part. Still looking for a more professional solution.

Either give the timezone to the client from the server (e.g., include it in the date string) or standardize the timezone on the server so that the client can assume a constant timezone. If you include the timezone with the date string, the below code snippet should work.
I havent tested this, but according to the docs, it should work:
String dateStr = "04/21/2011 01:37:36 -0800;
DateTimeFormat format = new DateTimeFormat("MM/dd/yyyy HH:mm:ss Z");
Date date = format.parse(dateStr);
Depending on how you are representing the timezone, you can change the final variable in the format string (the Z). See the docs for details: http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html

I did the following to parse a date in the TimeZone tz.
It's probably dodgy, but it works: -
final long MILLIS_IN_MINUTE = 60000;
Date localDate = DateTimeFormat.getFormat("dd MMM yyyy HH:mm:ss").parse(dateString);
int localOffset = localDate.getTimezoneOffset() * MILLIS_IN_MINUTE;
int targetOffset = tz.getOffset(localDate) * MILLIS_IN_MINUTE;
// Subtract the offset to make this into a UTC date.
return new Date(localDate.getTime() - localOffset + targetOffset);
It parses the date in the client timezone and then adjusts it to the required timezone.

Recently I passed upon this project: gwt-calendar-class which emulates Calendar and TimeZone in javascript.

public static Date getDateGWT(final String strDate, final int style) {
Date date = null;
int useStyle = style;
if (!validStyle(style)) {
useStyle = DEFAULT_DATE_STYLE;
}
if ((strDate != null) && (strDate.trim().length() > 0)) {
DateTimeFormat df = getDateFormatGWT(useStyle);
try {
date = df.parse(strDate);
} catch (Exception e) {
date = df.parse(date.toString());
}
}
return date;
}
private static DateTimeFormat getDateTimeFormatGWT(final int style) {
switch(style) {
case SHORT:
return DateTimeFormat.getShortDateTimeFormat();
case MEDIUM:
return DateTimeFormat.getMediumDateTimeFormat();
case LONG:
return DateTimeFormat.getLongDateTimeFormat();
case FULL:
return DateTimeFormat.getFullDateTimeFormat();
default :
return DateTimeFormat.getMediumDateTimeFormat();
}
}
Try This

Related

joda time parse method return format

I have very simple question - I read couple of threads here but I still do not understand how to get simple thing. I want to send string to method and get back joda date. I had no problem to build it up, but return format is 2015-03-11T17:13:09:000+01:00. How can I get desired (e.g. mmm-dd hh:mm) format back from below mentioned method (it mustto be a dateTime for sorting purposes on FX form)? I tried to gamble with another dateTimeFormatter but had no luck. Thank you very much in advance
public static DateTime stringToDateTime(String textDate) throws ParseException
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime jodaTime = dateTimeFormatter.parseDateTime(textDate);
return jodaTime;
}
What do you mean by "return format"? "Format" term here could only be related to a string representation of a DateTime object. That means you should specify format of your input string (what you've already done in your code) - and a corresponding DateTime object will be created. After that you probably use toString() to check the results, but DateTime.toString() uses ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ) according to JavaDoc - that gives you your 2015-03-11T17:13:09:000+01:00 result.
So to get it as desired you could try using toString(String pattern) method with format you need. But once again - it's just an output format to convert DateTime to String, it doesn't affect the datetime stored in your DateTime object.
I just use Calendar object so this is a possible way to do it:
static String stringToDateTime(String textDate) {
Calendar c = new GregorianCalendar();
// How you want the input to be formatted
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = df.parse(textDate);
c.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// How do you want to print your date
df= new SimpleDateFormat("dd-MM-yy");
return df.format(c.getTime());
}
// input
String myDate = "2015-04-15 14:25:25";
System.out.println(stringToDateTime(myDate));

Converting timestamp from parse.com in java

I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?
Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.

Setting default year in Joda Time

I am currently using the joda dateTime Api in my application. I am using the following code to parse multiple formats of dates into one single format. I am having trouble though when the format does not have a year. currently it sets the year as "2000".
Is there a way to set the year to a default if it is missing?
private static final DateTimeParser[] parsers = {
DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").getParser(),
DateTimeFormat.forPattern("[dd/MMM/yyyy:HH:mm:ss Z]").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").getParser(),
DateTimeFormat.forPattern("MMM-dd HH:mm:ss,SSS").getParser()
};
public static DateTime ConvertDate(String timestamp) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
DateTime date = formatter.parseDateTime(timestamp);
return date;
}
example:
Mar-07 13:59:13,219
becomes
2000-03-07T12:59:13.219-07:00
what I want :
example:
Mar-07 13:59:13,219
becomes
(currentyear)-03-07T12:59:13.219-07:00
You can use withDefaultYear():
public static DateTime convertDate(String timestamp) {
int stdYear = 1970; // example for new default year
DateTimeFormatter formatter =
new DateTimeFormatterBuilder().append(null, parsers).toFormatter()
.withDefaultYear(stdYear);
return formatter.parseDateTime(timestamp);
}
Since Joda 2.0 the default year is 2000 so that Feb 29 could be parsed correctly, check this.
Not sure if you can change that (check this with pivotYear), but as a bypass solution I would add current year to my timestamp if there wasn't any.

Java ParseException while attempting String to Date parsing

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Java String to Date without time

I'm taking a class in Java and I need to convert a string to a date format (dd/MM/yyyy). I have been using the SimpleDateFormat to format my input, but it is showing the time, timezone and day of the week the date falls. Here is a snippet of my code:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
do{
y = JOptionPane.showInputDialog(null,
"Please enter the vehicle's registration date",
"Year?",
JOptionPane.QUESTION_MESSAGE);
try {
date = df.parse(y);
check = true;
}
catch (ParseException e) {
check = false;
}
}
while (check == false);
return date;
Anyone know how I can keep the format to just the date (e.g. 12/3/2000)?
Thanks
Just format it accordingly using SimpleDateFormat#format().
String dateString = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);
The java.util.Date object contains information about both date and time. If you want only the date part in a human representable format, then you need to format it into a String. Invoking Date#toString() as you would get when doing System.out.println(dateObject) would only return the date in format dow mon dd hh:mm:ss zzz yyyy. Also see the linked javadoc.
I have a similar solution to #BalusC, except this one will provide a locale-dependent formatting:
String dateString = java.text.DateFormat.getDateInstance().format(dateObject);
In other words your US and EU customers will get different formatting. One they're familiar with.

Categories