简体   繁体   中英

Change Date to a string on the local time zone of the device

I am getting a Date datatype from the database like this Mon Sep 14 11:30:00 GMT+03:00 2020 .I want to change this value to a string so I used this function.

public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";


public static String dateToString(Date date){
    DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT);
    dateFormat.setTimeZone(TimeZone.getDefault());
    if(date == null)
        return "";
    return dateFormat.format(date);
}

This function is given me this output 2020-09-14 11:30 but it should be 2020-09-14 02:30 according to my android device time zone. Any suggestions ?

You could use java.time for this, it is made available to lower Android API levels via Android API Desugaring now.

public static void main(String[] args) {
    // (nearly) your example pattern for output (u is better here)
    final String DATE_FORMAT = "uuuu-MM-dd HH:mm";
    // use it to create an output formatter
    DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern(DATE_FORMAT);
    // your example String
    String exampleDate = "Mon Sep 14 11:30:00 GMT+03:00 2020";
    // parse it with a suitable formatter using a specific pattern and a Locale for names
    DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O uuuu",
                                                                Locale.ENGLISH);
    // then parse the example String
    OffsetDateTime odt = OffsetDateTime.parse(exampleDate, parserDtf);
    // get your local offset (the one of your device)
    ZoneOffset localOffset = OffsetDateTime.now().getOffset();
    // and adjust the offset to your local one
    OffsetDateTime localOdt = odt.withOffsetSameInstant(localOffset);
    // and output it (on android, use log...)
    System.out.println(odt.format(outputDtf));  // example datetime
    System.out.println(localOdt.format(outputDtf)); // same time in local offset
}

This code outputs

2020-09-14 11:30
2020-09-14 10:30

Please note that the output has — of course — taken my current offset, which is UTC+02:00.

Try out the getDefault() method of Locale

public static String dateToString(Date date){
    DateFormat dateFormat = new SimpleDateFormat(General.DATE_FORMAT, Locale.getDefault());
    dateFormat.setTimeZone(TimeZone.getDefault());
    if(date == null)
        return "";
    return dateFormat.format(date);
}

Hope it will work for you. Thank you.

尝试设置它之前

TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));

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