How to format date and time in Android?

前端 未结 24 1282
面向向阳花
面向向阳花 2020-11-22 00:51

How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?

24条回答
  •  你的背包
    2020-11-22 01:26

    I use it like this:

    public class DateUtils {
        static DateUtils instance;
        private final DateFormat dateFormat;
        private final DateFormat timeFormat;
    
        private DateUtils() {
            dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
            timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
        }
    
        public static DateUtils getInstance() {
            if (instance == null) {
                instance = new DateUtils();
            }
            return instance;
        }
    
        public synchronized static String formatDateTime(long timestamp) {
            long milliseconds = timestamp * 1000;
            Date dateTime = new Date(milliseconds);
            String date = getInstance().dateFormat.format(dateTime);
            String time = getInstance().timeFormat.format(dateTime);
            return date + " " + time;
        }
    }
    

提交回复
热议问题