1

我有一个格式为MM/DD/YYYY的日期和格式为HHMM的时间(24 小时制,不带冒号)。这两个字符串都在一个数组中。我想将其存储为一个字符串 - 可能类似于“MM-DD-YYYY HH:MM” - 然后在我展示它时能够将其转换为“2014 年 1 月 1 日 16:15”这样的书面日期给用户。我怎样才能做到这一点?

这是我拥有的代码:

String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);

然而,这就是我得到的:“Sun Dec 29 23:01:00 EST 2013”

我正在寻找的输出是:“December 29, 2013 23:01”

4

7 回答 7

2

SimpleDateFormat是要走的路;以所需的有意义的日期和时间格式解析您的字符串,最后将您的日期打印为所需的字符串。

您可以按如下方式指定 2 种格式:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");

考虑一个简单的硬编码日期和时间数组(不是最好的显示方式,但您的问题将其称为数组):

String[] array = { "12/31/2013", "1230" };

您必须在 Calendar 实例中设置这些解析日期:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());

最后使用相同的格式格式化您的日期SimpleDateFormat

SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");

这是完整的工作代码:

public class DateExample {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");

        String[] array = { "12/31/2013", "1230" };

        try {
            Date date = dateFormat.parse(array[0]);
            Date time = timeFormat.parse(array[1]);

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR, time.getHours());
            cal.add(Calendar.MINUTE, time.getMinutes());

            SimpleDateFormat newFormat = new SimpleDateFormat(
                    "MMMM dd, yyyy 'at' hh:mm");
            String datePrint = newFormat.format(cal.getTime());

            System.out.println(datePrint);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

输出:

2013 年 12 月 31 日 12:30

于 2013-12-31T20:48:59.263 回答
1

不幸的是,现有的答案都没有提到问题的根本原因,如下所示:

  • 您已使用D(指定Day in year)而不是dDay in month)。
  • 您已使用Y(指定Week year)而不是yYear)。

在文档页面了解更多信息。现在您已经了解了问题的根本原因,让我们专注于使用当时最好的标准 API 的解决方案。

java.time

旧的日期时间 API(java.util日期时间类型及其格式化 API SimpleDateFormat)已过时且容易出错。建议完全停止使用它并切换到java.time现代日期时间 API *

我将通过以下步骤解决它:

  1. 将日期字符串解析为LocalDate.
  2. 将时间字符串解析为LocalTime.
  3. 结合 和 的对象,LocalDate得到LocalTime的对象LocalDateTime
  4. 将对象格式化LocalDateTime为所需的模式。

使用现代 API 的演示:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // 1. Parse the date string into `LocalDate`.
        DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
        LocalDate date = LocalDate.parse("01/01/2014", dateParser);

        // 2. Parse the time string into `LocalTime`.
        DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
        LocalTime time = LocalTime.parse("1615", timeParser);

        // 3. Combine date and time to obtain an object of `LocalDateTime`.
        LocalDateTime ldt = date.atTime(time);

        // 4. Format the object of `LocalDateTime` into the desired pattern.
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
        String output = dtfOutput.format(ldt);
        System.out.println(output);
    }
}

输出:

January 1, 2014 16:15

Trail: Date Time了解有关现代日期时间 API *的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和您的 Android API 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

于 2021-05-08T15:33:29.103 回答
0

您可以使用 java.text.DateFormat 类将日期转换为字符串(格式方法),并将字符串转换为日期(解析方法)。

于 2013-12-31T19:54:43.150 回答
0

你可以用这个>>

    String s = sd.format(d);
    String s1 = sd1.format(d);

这是完整的代码>>

导入 java.text.SimpleDateFormat;导入 java.util.Date;

公共课 dt {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Date d = new Date();
    SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
    SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");



            String s = sd.format(d);
        String s1 = sd1.format(d);

    System.out.println(s +" "+ s1);

}

}

于 2014-01-01T01:14:10.307 回答
0

在发布之前,您应该费心做一些搜索。StackOverflow.com 已经有很多这样的问题和答案。

但为了后代,这里有一些使用Joda-Time 2.3 库的示例代码。避免与 Java 捆绑在一起的 java.util.Date/Calendar 类,因为它们的设计和实现都很糟糕。在 Java 8 中,继续使用 Joda-Time 或切换到JSR 310: Date and Time API定义的新java.time.* 类。这些新课程的灵感来自 Joda-Time,但完全重新设计。

Joda-Time 有许多旨在格式化输出的功能。Joda-Time 提供内置标准 (ISO 8601) 格式。某些类以适合主机区域设置的格式和语言呈现字符串,或者您可以指定区域设置。Joda-Time 还允许您定义自己的时髦格式。搜索“joda”+“format”会得到很多例子。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

String input = "05/27/2014" + " " + "23:01";

解析那个字符串……</p>

// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );

理想情况下,您可以将值以适当的日期时间格式存储在数据库中。如果不可能,则以 ISO 8601格式存储为字符串,设置为UTC /GMT(无时区偏移)。

// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.

通常在 UTC 中执行您的业务逻辑和存储。仅在应用的用户界面部分切换到本地时区和本地化格式。

// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );

转储到控制台...</p>

System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );

运行时……</p>

input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM
于 2014-01-01T01:18:32.217 回答
0

您可以SimpleDateFormat同时使用将字符串解析为日期并将日期格式化回字符串。这是您的示例:

    SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
    SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");

    String dateString = "05/27/2014 23:01";
    Date parsedDate = parser.parse(dateString);

    String formattedDateString = formatter.format(parsedDate);

    System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");

当我运行它时,我得到:

Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'

于 2013-12-31T20:42:40.577 回答
0

目标

  1. 使用您拥有的格式将字符串转换为日期
  2. 以您想要的格式将该日期输出为字符串

代码:

String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date  " +df); 
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));

输出:

date  Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
于 2013-12-31T20:42:48.593 回答