SimpleDateFormat parsing date differently on some android devices

后端 未结 2 1067
旧时难觅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

提交回复
热议问题