简体   繁体   中英

Change Time zone without change the date format

I have date format like "EEE, dd MMM yyyy HH:mm:ss Z" , and the date is

String date = "Tue, 14 Aug 2012 07:26:33 +0000";

How to change to +0700 time zone without change the date format?

This is what I try

String sDate = null;
Date date = null;
try {
    sDate = "Tue, 14 Aug 2012 07:26:33 +0000";
    SimpleDateFormat curFormater = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    curFormater.setTimeZone(TimeZone.getTimeZone("GMT"));
    try {
        date = curFormater.parse(sDate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} catch (DropboxException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
lastUpdate.setText("Last Update : " + date.toString());

but the result is Tue Aug 14 14:26:33 ICT 2012

You're nearly there, you've parsed the date correctly, but you're relying on the default toString() instead of the format you've already created.

Try this instead for the last line:

lastUpdate.setText(curFormater.format(date));

Alternatively, if you want to add a manual number of hours, you could do it something like this:

static final Long oneHourInMilliseconds = new Long(3600000);
static final DateFormat d = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");

public static Long addHours(Date time, int hours)
{
    return time.getTime() + (hours * oneHourInMilliseconds);
}

public static void main(String[] args) throws ParseException
{
    String dateAsString = "Tue, 14 Aug 2012 07:26:33 +0000";
    Date before = d.parse(dateAsString);
    Date after = new Date(addHours(before, 7));
    System.out.println("Before: " + before + ". After: " + after);
}

date -d在Unix中适用于此。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM