SimpleDateFormat returns 不同的结果

SimpleDateFormat returns different result

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

这是结果:

Sun Jun 23 00:00:00 GMT+08:00 2019

这是我需要的:

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();
            }
        }
    };

试试这个对我来说效果很好,可以将长日期转换为简单日期。

public String getTimeStamp(long timeinMillies) {
            String date = null;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // modify format
            date = formatter.format(new Date(timeinMillies));
            System.out.println("Today is " + date);

            return date;
        }

或者使用这个

SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date(year, month, day);
String strDate = dateFormatter.format(d);

谢谢,编码愉快...

在扩展中添加这个功能它会起作用

   fun Context.getFormattedDate(
        inputFormat: String = "yyyy-MM-dd",
        outputFormat: String,
        inputDate: String,
        locale: Locale = Locale("EN")
    ): String {
        val inputFormat = inputFormat
        var outputFormat = outputFormat

        if (outputFormat == "") {
            outputFormat = "EEEE d 'de' MMMM 'del' yyyy" // if inputFormat = "", set a default output format.
        }
        var parsed: Date? = null
        var outputDate = ""

        val dfInput = SimpleDateFormat(inputFormat, locale)
        val dfOutput = SimpleDateFormat(outputFormat, locale)

        try {
            parsed = dfInput.parse(inputDate)
            outputDate = dfOutput.format(parsed)
        } catch (e: Exception) {
            Log.e("formattedDateFromString", "Exception in formate Date From string(): " + e.message)
            e.printStackTrace()
        }
        return outputDate

    }

这将是您想要的结果

String date = year+"-"+month+"-"+dayOfMonth;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", 

    Locale.getDefault());
            Date datex = null;
            try {
                datex = format.parse(date);
                String formattedDate=format.format(datex);
                Log.e("FormattedDate",formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

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

        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();
        }

使用此函数进行任何日期转换,它会起作用:)

在Java

/**
 * Changes date format from one format to another format.
 *
 * @param fromFormat format of received date string.
 * @param toFormat   format of returned(needed) date string.
 * @param date       date whose format is to be changed in string.
 * @return date string formatted into toFormat
 */
public static String changeDateFormat(String fromFormat, String toFormat, String date) {
    SimpleDateFormat toDateFormat = new SimpleDateFormat(toFormat);
    SimpleDateFormat dateFormat = new SimpleDateFormat(fromFormat);

    try {
        return toDateFormat.format(dateFormat.parse(date));
    } catch (Exception e) {
        e.printStackTrace();
        return "NA";
    }
}

在 Kotlin 中

fun changeDateFormat(fromFormat: String, toFormat: String, date: String): String {
        val toDateFormat = SimpleDateFormat(toFormat)
        val dateFormat = SimpleDateFormat(fromFormat)
        return try {
            toDateFormat.format(dateFormat.parse(date))
        } catch (e: Exception) {
            e.printStackTrace()
            "NA"
        }

    }

在代码中

AppLogs.e(
        "DATE",
        Utility.changeDateFormat("E MMM dd HH:mm:ss Z yyyy", "yyyy-MM-dd", "Sun Jun 23 00:00:00 GMT+05:30 2019")
    )

java.time 和 ThreeTenABP

这将为您提供您要求的输出,2019-07-23(正确的月份编号 07,并带有前导零):

onDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            LocalDate date = LocalDate.of(year, month + 1, dayOfMonth);
            String dateString = date.toString();
            System.out.println(dateString);
        }
    };

我正在使用来自 java.time 的 LocalDate,现代 Java 日期和时间 API。我们需要在月份上加一个,因为 DatePicker 从 1 月的 0 到 12 月的 11 令人困惑地计算月份,而 LocalDate 以与人类相同的方式计算月份。 LocalDate.toString() 生成您要求的 yyyy-MM-dd 格式。它符合 ISO 8601。

你的代码出了什么问题?

首先是因为,如前所述,DatePicker 从 0 开始对月份进行编号,你弄错了月份,6 表示 7 月,所以它在输出中打印为 6 月。其次,将日期格式化为字符串,将其解析为 Date 并将 Date 打印为字符串是 over-complicating 的事情。另外 Date.toString() 总是生成您看到的格式 EEE MMM dd HH:mm:ss zzz yyyy。要生成与您需要明确格式化的字符串不同的字符串。

在任何情况下,SimpleDateFormatDate 都设计不佳且早已过时。现代日期和时间 API 更易于使用。热烈推荐

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6.

  • 在 Java 8 和更新的 Android 设备上(从 API 级别 26)现代 API 出现 built-in.
  • 在 Java 6 和 7 中获取现代 类 的 ThreeTen Backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 类。

链接