SimpleDateFormat parsing date differently on some android devices

后端 未结 2 1068
旧时难觅i
旧时难觅i 2021-01-27 13:25

I am parsing the date as:

public class Consts{
public static final SimpleDateFormat DATE_FORMATTER_WITHOUT_TIME_ZONE = new SimpleDateFormat(
            \"yyyy-M         


        
相关标签:
2条回答
  • 2021-01-27 14:24

    You can extend SimpleDateFormat and override its format(...) function as following:

    public class ExSimpleDateFormat extends SimpleDateFormat{
    
        private static final long serialVersionUID = -8275126788734707527L;
    
        public ExSimpleDateFormat() {
    
            super();
        }
    
        public ExSimpleDateFormat(String string, Locale us) {
    
            super(string, us);
        }
    
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
        {            
            final StringBuffer buf = super.format(date, toAppendTo, pos);
            buf.insert(buf.length() - 2, ':');
            return buf;
        };
    }
    

    And execute following code:

    Calendar ca = Calendar.getInstance();       
    ca.setTimeInMillis(System.currentTimeMillis());
    ExSimpleDateFormat exSimpleDateFormat = new ExSimpleDateFormat("dd-MM-yyyy HH:mm:ss 'GMT'Z", Locale.US);
    exSimpleDateFormat.setTimeZone(ca.getTimeZone()); //your device timezone which can be GMT+xx:yy or GMT-xx:yy
    String desiredTime = exSimpleDateFormat.format(ca.getTime());
    

    Output would be like: 23-03-2015 23:12:52 GMT+05:00

    Let me know if it helps. Thanks

    0 讨论(0)
  • 2021-01-27 14:28

    The difference is caused by different locales set up on devices.

    To mitigate the locale differences, you should use particular locale while formatting the date string. Here is a sample from my code, solving the same issue:

    new SimpleDateFormat(C.FORMAT_DATETIMEZ, Locale.US).format(new Date(time))
    
    0 讨论(0)
提交回复
热议问题