【问题标题】:How to set 24-hours format for date on java?如何在 java 上设置日期的 24 小时格式?
【发布时间】:2012-02-13 00:25:04
【问题描述】:

我一直在开发使用此代码的 Android 应用程序:

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(d);

我需要从当前时刻开始 8 小时后获取日期,并且我希望该日期具有 24 小时格式,但我不知道如何通过 SimpleDateFormat 进行设置。我还需要该日期具有DD/MM/YYYY HH:MM:SS 格式。

【问题讨论】:

标签: java android datetime


【解决方案1】:

这将为您提供 24 小时格式的日期。

    Date date = new Date();
    date.setHours(date.getHours() + 8);
    System.out.println(date);
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.format(date));

【讨论】:

  • 我没有足够的时间来测试它,但是有人告诉“如果你使用 kk,你会得到像 24:30 这样的结果,但如果你使用 HH,你会得到像 00:30 这样的结果” [来源:stackoverflow.com/a/7078488/421467]。这是真的吗?
  • setHours 已弃用。
  • 这种方法的问题是 Java 将午夜报告为 24:00 而不是标准的 00:00。
【解决方案2】:

你可以这样做:

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);

这里 'kk:mm:ss' 是正确答案,我与 Oracle 数据库混淆了,抱歉。

【讨论】:

    【解决方案3】:

    试试下面的代码

        String dateStr = "Jul 27, 2011 8:35:29 PM";
        DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
        DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
           date = readFormat.parse( dateStr );
        } catch ( ParseException e ) {
            e.printStackTrace();
        }
    
        String formattedDate = "";
        if( date != null ) {
        formattedDate = writeFormat.format( date );
        }
    
        System.out.println(formattedDate);
    

    祝你好运!!!

    检查各种formats

    【讨论】:

      【解决方案4】:
      Date d=new Date(new Date().getTime()+28800000);
      String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
      

      HH 将返回 0-23 几个小时。

      kk 将返回 1-24 小时。

      在此处查看更多信息:Customizing Formats

      使用方法 setIs24HourView(Boolean is24HourView) 设置时间选择器以设置 24 小时视图。

      【讨论】:

      • 这仍然是最正确的答案。我将进行编辑以使其更清楚,因为我不确定您在说什么。此外,上述答案中的链接也解释了。
      • @jeet 哪个更常见,0-23 还是 1-24?
      • @simgineer 我在我记得的所有情况下都见过 0-23(我不记得见过像 24:30 这样的东西)。
      【解决方案5】:

      tl;博士

      现代方法使用 java.time 类。

      Instant.now()                                        // Capture current moment in UTC.
             .truncatedTo( ChronoUnit.SECONDS )            // Lop off any fractional second.
             .plus( 8 , ChronoUnit.HOURS )                 // Add eight hours.
             .atZone( ZoneId.of( "America/Montreal" ) )    // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
             .format(                                      // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
                 DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
                                  .withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated. 
             )                                             // Returns a `String` object.
      

      23/01/2017 15:34:56

      java.time

      仅供参考,旧的 CalendarDate 课程现在是 legacy。由java.time 类取代。大部分 java.time 都向后移植到 Java 6、Java 7 和 Android(见下文)。

      Instant

      使用Instant 类捕捉UTC 中的当前时刻。

      Instant instantNow = Instant.now();
      

      instant.toString(): 2017-01-23T12:34:56.789Z

      如果您只想要整秒,而不需要任何小数秒,请截断。

      Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
      

      instant.toString(): 2017-01-23T12:34:56Z

      数学

      Instant 班级可以做数学,增加了一定的时间。通过ChronoUnit 枚举指定要添加的时间量,TemporalUnit 的实现。

      instant = instant.plus( 8 , ChronoUnit.HOURS );
      

      instant.toString(): 2017-01-23T20:34:56Z

      ZonedDateTime

      要通过特定地区挂钟时间的镜头查看同一时刻,请应用ZoneId 以获取ZonedDateTime

      continent/region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

      ZoneId z = ZoneId.of( "America/Montreal" );
      ZonedDateTime zdt = instant.atZone( z );
      

      zdt.toString(): 2017-01-23T15:34:56-05:00[美国/蒙特利尔]

      生成字符串

      您可以通过在DateTimeFormatter 对象中指定格式模式来生成所需格式的字符串。

      请注意,格式化模式中的字母大小写很重要。问题的代码有 hh 表示 12 小时时间,而大写 HHjava.time.DateTimeFormatter 和旧版 java.text.SimpleDateFormat 中都是 24 小时时间 (0-23)。

      java.time 中的格式代码与旧版SimpleDateFormat 中的格式代码相似,但并不完全相同。仔细研究课堂文档。在这里,HH 恰好工作相同。

      DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
      String output = zdt.format( f );
      

      自动定位

      考虑让 java.time 通过调用 DateTimeFormatter.ofLocalizedDateTime 来完全本地化 String 文本的生成,而不是硬编码格式模式。

      顺便说一句,请注意时区和Locale 彼此之间没有任何关系;正交问题。一是关于content,意思是(挂钟时间)。另一个是关于表示,确定用于向用户展示该含义的人类语言和文化规范。

      Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
      ZoneId z = ZoneId.of( "Pacific/Auckland" );  // Notice that time zone is unrelated to the `Locale` used in localizing.
      ZonedDateTime zdt = instant.atZone( z );
      
      DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                                             .withLocale( Locale.CANADA_FRENCH );  // The locale determines human language and cultural norms used in generating the text representing this date-time object.
      String output = zdt.format( f );
      

      instant.toString(): 2017-01-23T12:34:56Z

      zdt.toString(): 2017-01-24T01:34:56+13:00[太平洋/奥克兰]

      输出:mardi 2017 年 1 月 24 日 à 01:34:56 heure avancée de la Nouvelle-Zélande


      关于java.time

      java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

      Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

      要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

      您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

      从哪里获得 java.time 类?


      乔达时间

      更新:Joda-Time 项目现在位于maintenance mode,团队建议迁移到java.time 类。

      Joda-Time 让这种工作变得更加容易。

      // © 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.*;
      
      DateTime later = DateTime.now().plusHours( 8 );
      DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
      String laterAsText = formatter.print( later );
      
      System.out.println( "laterAsText: " + laterAsText );
      

      运行时……

      laterAsText: 19/12/2013 02:50:18
      

      请注意,此语法使用默认时区。更好的做法是使用显式 DateTimeZone 实例。

      【讨论】:

      • Androiders:Instant 需要 API 级别 26。
      • @VonSchnauzer 对于 26 岁之前的 Android,请参阅我标记为“Android”的项目符号中链接的 ThreeTen-BackportThreeTenABP 项目。
      【解决方案6】:

      试试这个...

      Calendar calendar = Calendar.getInstance();
      String currentDate24Hrs = (String) DateFormat.format(
                  "MM/dd/yyyy kk:mm:ss", calendar.getTime());
      Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);
      

      【讨论】:

        【解决方案7】:

        12 小时制:

        SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);
        

        24 小时制:

        SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);
        

        【讨论】:

        • 为什么这没有被标记为正确答案..?为什么要手动添加东西然后测试呢?
        • 这是最好的方法,因为午夜正确地报告为 00:00 而不是 24:00。
        【解决方案8】:

        在格式化字符串中使用 HH 而不是 hh

        【讨论】:

          【解决方案9】:

          您只需将模式中的小写“hh”更改为大写字母“HH”

          对于 Kotlin:

          val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())

          对于java:

          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())

          【讨论】:

            【解决方案10】:

            LocalDateTime#plusHours

            LocalDateTimeISO-8601 standards 为模型,并作为JSR-310 implementation 的一部分与Java-8 一起引入。

            使用LocalDateTime#plusHours 获取此LocalDateTime 的副本,并添加指定的小时数。

            import java.time.LocalDateTime;
            import java.time.ZoneId;
            import java.time.format.DateTimeFormatter;
            import java.util.Locale;
            
            public class Main {
                public static void main(String[] args) {
                    // ZoneId.systemDefault() returns the timezone of your JVM. It is also the
                    // default timezone for date-time type i.e.
                    // LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
                    // Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
                    LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
                    System.out.println(ldt);
            
                    LocalDateTime after8Hours = ldt.plusHours(8);
                    System.out.println(after8Hours);
            
                    // Custom format
                    DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
                    DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
                    System.out.println(dtfTimeFormat24H.format(after8Hours));
                    System.out.println(dtfTimeFormat12h.format(after8Hours));
                }
            }
            

            输出:

            2021-01-07T15:24:52.736612
            2021-01-07T23:24:52.736612
            07/01/2021 23:24:52
            07/01/2021 11:24:52 PM
            

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

            使用旧版 API:

            import java.text.SimpleDateFormat;
            import java.util.Calendar;
            import java.util.Date;
            import java.util.Locale;
            import java.util.TimeZone;
            
            public class Main {
                public static void main(String[] args) {
                    Calendar calendar = Calendar.getInstance();
                    Date currentDateTime = calendar.getTime();
                    System.out.println(currentDateTime);
            
                    // After 8 hours
                    calendar.add(Calendar.HOUR_OF_DAY, 8);
                    Date after8Hours = calendar.getTime();
                    System.out.println(after8Hours);
            
                    // Custom formats
                    SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
                    // Change the timezone as per your requirement e.g.
                    // TimeZone.getTimeZone("Europe/London")
                    sdf24H.setTimeZone(TimeZone.getDefault());
            
                    SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
                    sdf12h.setTimeZone(TimeZone.getDefault());
            
                    System.out.println(sdf24H.format(after8Hours));
                    System.out.println(sdf12h.format(after8Hours));
                }
            }
            

            输出:

            Thu Jan 07 15:34:10 GMT 2021
            Thu Jan 07 23:34:10 GMT 2021
            07/01/2021 23:34:10
            07/01/2021 11:34:10 PM
            

            一些重要说明:

            1. 日期时间对象应该存储有关日期、时间、时区等的信息,而不是格式。您可以使用日期时间格式化 API 使用您选择的模式将日期时间对象格式化为 String
              • 现代日期时间类型的日期时间格式化 API 在包中,java.time.format 例如java.time.format.DateTimeFormatterjava.time.format.DateTimeFormatterBuilder
              • 旧日期时间类型的日期时间格式化 API 在包中,java.text 例如java.text.SimpleDateFormatjava.text.DateFormat
            2. java.util.Date 对象不像modern date-time types 那样是真正的日期时间对象;相反,它表示距离Epoch of January 1, 1970 的毫秒数。当你打印一个java.util.Date 的对象时,它的toString 方法返回JVM 时区中的日期时间,从这个毫秒值计算。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFormat 并从中获取格式化字符串。
            3. java.util 的日期时间 API 及其格式 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到modern date-time API

            【讨论】:

              猜你喜欢
              • 2023-04-06
              • 2023-02-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-08
              • 2011-11-05
              相关资源
              最近更新 更多