Search code examples
javadatetimedatetimeoffsetjava-6java.util.date

How to save DateTime as Date with TimeZone offset included?


I have some DateTime including TimeZone Europe/Vienna (+0200). It is fetched by this method:

settlementService.getPendingPeriodStart()

and look with toString like this:

2012-06-01T00:00:00.000+02:00

Now I want to save this date 2012-06-01 as java.util.Date, so I tried something like this:

transactionDate = settlementService.getPendingPeriodStart().withTime(0, 0, 0, 0).toDate();

But the result is this:

Thu May 31 22:00:00 UTC 2012

What's the best way to save the DateTime result as Date including the TimeZone offset, so transactionDate should be 2012-06-01. I could tinker with GregorianCalendar, but that's not what I like. This ought to be easier, isn't it?

By the way (if this isn't clear). The local system runs on UTC. That's why the result is Thu May 31 22:00:00 UTC 2012.


Solution

  • I think I found a solution. (If you know a better solution, just let me know)

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    DateTime dateTimeWithTimeZone = new DateTime(DateTimeZone.forID("Europe/Vienna")).withDate(2012, 06, 01).withTime(0, 0, 0, 0);      
    Date dateWithTimeZoneIncluded = dateTimeWithTimeZone.toLocalDate().toDate();
    
    System.out.println(dateFormat.format(dateWithTimeZoneIncluded));
    

    The result is 2012-06-01 as expected.