首页 > 解决方案 > SimpleDateFormat 返回不同的结果

问题描述

我正在尝试将 a 解析string为 a SimpleDateFormat,但是它不显示yyyy-MM-dd我制作的格式。

这是结果:

2019 年 6 月 23 日星期日 00:00:00 GMT+08:00

这就是我需要的:

2019-07-23

这是我的代码:

 onDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year+"-"+month+"-"+dayOfMonth;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            try {
                Date datex = format.parse(date);
                System.out.println(datex);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    };

标签: javaandroiddatesimpledateformatdate-parsing

解决方案


通过以下更简单的方法来做到这一点,

        String date = year+"-"+month+"-"+dayOfMonth;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        try {
            Date datex = format.parse(date);
            String outputDate = format.format(datex);
            System.out.println(outputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

推荐阅读