Setting default year in Joda Time - java

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.

Related

How to compare date in firestore [duplicate]

I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
Something like this should do the trick:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
To add one day, per the question asked, call it as follows:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
java.time
On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)
Assuming String input and output:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Construct a Calendar object and call add(Calendar.DATE, 1);
Java 8 added a new API for working with dates and times.
With Java 8 you can use the following lines of code:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
Take a look at Joda-Time (https://www.joda.org/joda-time/).
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
Please note that this line adds 24 hours:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
but this line adds one day
cal.add( Calendar.DATE, 1 );
On days with a daylight savings time change (25 or 23 hours) you will get different results!
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.
If you are using Java 8, then do it like this.
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
If you want to use SimpleDateFormat, then do it like this.
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);
This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
It's very simple, trying to explain in a simple word.
get the today's date as below
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);
Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.
System.out.println(calendar.getTime());// print modified date which is tomorrow's date
Thanks
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
With Java SE 8 or higher you should use the new Date/Time API
int days = 7;
LocalDate dateRedeemed = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
String newDate = dateRedeemed.plusDays(days).format(formatter);
System.out.println(newDate);
If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.
public LocalDate asLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
return zdt.toLocalDate();
}
With a version prior to Java SE 8 you may use Joda-Time
Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8
int days = 7;
DateTime dateRedeemed = DateTime.now();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
String newDate = dateRedeemed.plusDays(days).toString(formatter);
System.out.println(newDate);
Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.
Just pass date in String and number of next days
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
Will Print:
1970-12-31
1971-01-01
1970-12-31
Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
It's simple actually.
One day contains 86400000 milliSeconds.
So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then
add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.
Example
String Today = new Date(System.currentTimeMillis()).toString();
String Today will be 2019-05-9
String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();
String Tommorow will be 2019-05-10
String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();
String DayAfterTommorow will be 2019-05-11
You can use this package from "org.apache.commons.lang3.time":
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);
If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.
I'm working with a date in this format: yyyy-mm-dd
You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.
yyyy-MM-dd is the default format of java.time.LocalDate
The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.
Ways to increment a local date by one day
There are three options:
LocalDate#plusDays(long daysToAdd)
LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Parsing
LocalDate ldt = LocalDate.parse("2020-10-20");
System.out.println(ldt);
// Incrementing by one day
LocalDate oneDayLater = ldt.plusDays(1);
System.out.println(oneDayLater);
// Alternatively
oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
System.out.println(oneDayLater);
oneDayLater = ldt.plus(Period.ofDays(1));
System.out.println(oneDayLater);
String desiredString = oneDayLater.toString();
System.out.println(desiredString);
}
}
Output:
2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21
How to switch from the legacy to the modern date-time API?
You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odt);
// Alternatively, using time-zone
odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odt);
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
System.out.println(ldt);
// Alternatively,
ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016
Learn more about the modern Date-Time API from Trail: Date Time.
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Convert to string and back with SimpleDateFormat: This is an inefficient solution.
Convert to LocalDate: You would lose any time-of-day information.
Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
You can do this just in one line.
e.g to add 5 days
Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));
to subtract 5 days
Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));

Retrieving a DateTime Using resultset into a DateTime field [duplicate]

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.
....
while(resultSet.next()) {
Timestamp dtStart = resultSet.getTimestamp("dtStart");
Timestamp dtEnd = resultSet.getTimestamp("dtEnd");
// I would like to then have the date and time
// converted into the formats mentioned...
....
}
....
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.
java.time
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd.
I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();
Converts this Timestamp object to a code LocalDateTime.
The conversion creates a code LocalDateTime that represents the
same year, month, day of month, hours, minutes, seconds and nanos
date-time value as this code Timestamp in the local time zone.
since 1.8

Combining two Date instance to create date-time using Joda

I have two java.util.Date instances which is contain date value and time value. now I want to combine these values to create single java.util.Date instance representing the date and time.
here some example to make clear what I'd want :
Date date = 2015-06-01;
Date time = 22:30;
combine into :
Date dateTime = 2015-06-01 22:30;
I do some search and I found this question
Combining java.util.Dates to create a date-time
which is similar with my current issue. But the chosen answer on that question is deprecated.
You can do it without JODA, by using Calendar
However, as you asked about JODA, here is the way to do in JODA:
// you want the date part from it
Date d = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-01-02 03:04:05");
// you want to time part from it
Date t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-02-03 04:05:06");
LocalDate datePart = new LocalDate(d);
LocalTime timePart = new LocalTime(t);
LocalDateTime dateTime = datePart.toLocalDateTime(timePart);
Date result = dateTime.toDate();
// Or shrink the above 4 lines into one, as follow
// Date result = new LocalDate(d).toLocalDateTime(new LocalTime(t)).toDate();
System.out.println("result " + result);
// print out result Wed Jan 02 04:05:06 CST 2013
Use a Calendar instead?
In particular, set(int year,
int month,
int date,
int hourOfDay,
int minute) and
if you want a Date, use getTime() ?
or convert the Date object to a Calendar object using the setTime(Date ..) function from the Calendar class, extract the values (day, hours, minute) using functions from the Calendar class?

JXL and Timezone writing an Excel

I try to create an Excel sheet with jxl.
One of my field is a Date, and I live in GMT+1 TimeZone
I use something like this to do it:
WritableCellFormat EXCEL_DATE_FORMATTER = new WritableCellFormat(new DateFormat("dd/MM/yyyy hh:mm"));
...
WritableCell cell = null;
cell = new jxl.write.DateTime(col, row, date);
cell.setCellFormat(EXCEL_DATE_FORMATTER);
The date is writing in the correct format but with a -1 hour value (in GMT)
I try to find a solution and i found this
http://www.andykhan.com/jexcelapi/tutorial.html#dates
But I can't pass a SimpleDateFormat to a DateCell.
There is a way to do it?
Now I using java.util.Calendar to add an hour, but is an horrible solution.
Thank for help!
The jxl.write.DateTime class has several constructors (cf. API).
By default, it will use your system TimeZone to modify the date. You can pass to the constructor a jxl.write.DateTime.GMTDate object to disable this. Here is the code you should use:
WritableCell cell = null;
cell = new jxl.write.DateTime(col, row, date, DateTime.GMT);
Yesterday I had a same issue. I live in CET time zone (Central European Time) and simple creation of the DateTime cell moved the time about one hour.
At first I tried to set the timezone on GMT as is suggested in the official tutorial.
final DateFormat valueFormatDate = new DateFormat( "dd.MM.yyyy HH:mm" );
valueFormatDate.getDateFormat().setTimeZone( TimeZone.getTimeZone( "GMT" ) );
It appears not to be working. The time modification was still same. So I tried to set up correct timezone to match the timezone in a Date object.
final DateFormat valueFormatDate = new DateFormat( "dd.MM.yyyy HH:mm" );
valueFormatDate.getDateFormat().setTimeZone( TimeZone.getTimeZone( "CET" ) );
This worked perfectly as I expected. But the things not to be too easy, there is except CET timezone also CEST (Central European Summer Time) which moves the time about another hour. When I tried to use dates in CEST time, it didn't worked again because there was one hour addition to the expected base. I guess that it would be solution to set up "CEST" timezone instead of "CET" for them but I didn't figure out how to get the proper timezone from the Calendar, it always returned CET.
Anyway finally I used a not nice, but reliably working solution.
I have a factory method for date cell to have a configuration on one single place
in that method, I convert the given Date to be in GMT timezone at first
set up the timezone format to GMT
disable timezone modification on DateTime cell.
These steps are not absolutely clean but it works for CET as well as CEST dates. The final code is here:
public class DateUtils {
// formatter to convert from current timezone
private static final SimpleDateFormat DATE_FORMATTER_FROM_CURRENT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// formatter to convert to GMT timezone
private static final SimpleDateFormat DATE_FORMATTER_TO_GMT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
static {
// initialize the GMT formatter
final Calendar cal = Calendar.getInstance( new SimpleTimeZone( 0, "GMT" ) );
DATE_FORMATTER_TO_GMT.setCalendar( cal );
}
public static Date toGMT( final Date base ) {
try {
// convert to string and after that convert it back
final String date = DATE_FORMATTER_FROM_CURRENT.format( base );
return DATE_FORMATTER_TO_GMT.parse( date );
} catch ( ParseException e ) {
log.error( "Date parsing failed. Conversion to GMT wasn't performed.", e );
return base;
}
}
}
And there is a factory method
/** builds date cell for header */
static WritableCell createDate( final int column, final int row, final Date value ) {
final DateFormat valueFormatDate = new DateFormat( "dd.MM.yyyy HH:mm" );
valueFormatDate.getDateFormat().setTimeZone( TimeZone.getTimeZone( "GMT" ) );
final WritableCellFormat formatDate = new WritableCellFormat( valueFormatDate );
// create cell
return new DateTime( column, row, toGMT( value ), formatDate, DateTime.GMT );
}

How to parse date string using Timezone in GWT

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

Categories