简体   繁体   English

如何将24小时的字符串转换为标准的java日期,反之亦然?

[英]How to convert 24hr timestring to standard java Date vice versa?

I would like to have two functions: 我想有两个功能:

  1. Say I have the date in a string "11/12/2011" and time in a String: "0200" . 假设我在字符串"11/12/2011"有日期,时间在字符串中: "0200" I would like a simple function (if possible) that takes two parameters (the date and time from above) in java that converts it into 11/12/2011 2:00AM in a Java Date object. 我想要一个简单的函数(如果可能的话),它在java中将两个参数(来自上面的日期和时间)转换为Java Date对象中的11/12/2011 2:00 AM。

  2. Say I have a java Date object as the only parameter (eg 11/12/2011 2:00AM) that returns the military time from it, (eg "0200"). 假设我有一个java Date对象作为唯一参数(例如11/12/2011 2:00 AM)从中返回军事时间(例如“0200”)。

Is there some java library or what is the best way to accomplish the above? 是否有一些java库或者什么是实现上述目标的最佳方法? Or is there something built into java Date that makes it easy to get something in military time to normal time Java date uses? 或者是否有一些内置于Java Date中的东西可以让你在军事时间内轻松获得Java日期使用的正常时间?

new SimpleDateFormat("MM/dd/yyyy HHmm").parse("11/12/2011" + " " + "0200");
new SimpleDateFormat("MM/dd/yyyy HHmm").format(new Date());
new SimpleDateFormat("HHmm").format(new Date());

(assuming the military in the US still put month first in dates). (假设美国的军队仍然把月份放在第一个日期)。

[edit: you need to worry about your time zone too - for parsing it's often easiest to simply append this. [编辑:你也需要担心你的时区 - 解析它通常最简单地附加它。 for example: 例如:

new SimpleDateFormat("MM/dd/yyyy HHmm Z").parse("11/12/2011" + " " + "0200" + " PST");

(maybe the military always use UTC? i have no idea...). (也许军方总是使用UTC?我不知道......)。 and for formatting, you can set the timezone on the SDF instance using setTimezone().] 对于格式化,您可以使用setTimezone()在SDF实例上设置时区。

您可以将SimpleDateFormat.parse与适当的格式字符串一起使用。

Thats how I did it 多数民众赞成我是怎么做到的

public static String militaryToOrdinaryTime(int milTime)
    {
       int hour = milTime / 100;
       int min = milTime % 100;
       String period;

       if (hour < 0 || hour > 24 || min < 0 || min > 59)
       {
           return "";
       }
       else if (hour > 12)
       {
           hour = hour - 12;
           period = "pm";
       }
       else
       {
           period = "am";
       }
       if (hour == 0)
       {
           hour = 12;
       }
       else if (min == 0)
       {
           String ordTime = hour + " " + period;
           return ordTime;
       }  
       else if (min < 10 && min > 0)
       {
          String min1 = String.valueOf(min);
min1 = "0" + min1;
String ordTime = hour + ":" + min1 + " " + period;
return ordTime;
       }
       String ordTime = hour + ":" + min + " " + period;
       return ordTime;
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        int time = in.nextInt();

        System.out.println(militaryToOrdinaryTime(time));
    }
}

That's how I did. 这就是我做的。

Here is my code: 这是我的代码:

import java.util.Scanner;

class test{
int h,m,s;

public static void main (String args[]){
    int hour,min,sec;
    String format;
    Scanner obj=new Scanner(System.in);
    hour=obj.nextInt();
    min=obj.nextInt();
    sec=obj.nextInt();
    format=obj.next();
    int h,m,s;

    h=((hour>=00&&hour<24)?hour:0);
    m=((min>=00&&min<60)?min:0);
    s=((sec>=00&&sec<60)?sec:0);

    if(format.equals("PM")){
        h= (h!=12? 12+h :h);
    }else if (h==12)h=0;
    System.out.print(h+":"+m+":"+s);

}}

tl;dr TL;博士

LocalDateTime ldt = LocalDateTime.of( 
    LocalDate.parse( 
        "11/12/2011" , 
        DateTimeFormatter.ofPattern( "mm/DD/uuuu" ) 
    ) 
    , 
    LocalTime.parse( 
        "0200" ,
        DateTimeFormatter.ofPattern( "HHmm" ) 
    )
)

24-hour clock is “normal” 24小时时钟 “正常”的

No such thing as "normal time" and "military time". 没有“正常时间”和“军事时间”这样的东西。 Most people on the planet are fluent in both 12-hour clock time for casual use and 24-hour clock time for important matters such as train schedule. 这个星球上的大多数人都可以在12小时的休闲时间和24小时的时间内熟练掌握火车时刻表等重要事项。 The term "military time" is mostly used in the United States where oddly few people outside the military know 24-hour time. “军事时间”一词主要用于美国,军队以外的人很少有24小时的时间。

Avoid legacy date-time classes 避免遗留日期时间类

Avoid the troublesome old date-time classes such as java.util.Date and .Calendar . 避免麻烦的旧日期时间类,如java.util.Date.Calendar Now supplanted by the java.time classes. 现在取代了java.time类。

You have a date-only value and a time-of-day value, and you want to combine them. 您有一个仅限日期的值和一个时间值,并且您希望将它们组合在一起。 So first establish each part. 所以首先建立每个部分。

The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有时间且没有时区的仅日期值。 Similarly, the LocalTime class represents a time-of-day without a date and without a time zone. 同样, LocalTime类表示没有日期且没有时区的时间。

LocalDate

You can specify an explicit formatting pattern. 您可以指定显式格式设置模式。

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "mm/DD/uuuu" ).withLocale( Locale.US );
LocalDate ld = LocalDate.parse( "11/12/2011" , dateFormatter );

ld.toString(): 2011-01-12 ld.toString():2011-01-12

LocalTime

And do the same for time-of-day. 并为时间做同样的事情。

DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern( "HHmm" );
LocalTime lt = LocalTime.parse( "0200" , timeFormatter );

lt.toString(): 02:00 lt.toString():02:00

LocalDateTime

Join these two parts into a LocalDateTime . 将这两部分加入LocalDateTime

LocalDateTime ldt = LocalDateTime.of( ld , lt );

This LocalDateTime does not represent an actual moment, a point on the timeline. LocalDateTime 并不代表实际的时刻,在时间轴上的一个点。 This object has no real meaning without the context of an offset-from-UTC or a time zone. 没有偏离UTC或时区的上下文,此对象没有实际意义。 The moment of 2 AM in Auckland NZ is hours earlier than 2 AM in Kolkata IN which is hours earlier than 2 AM in Paris FR and still later is 2 AM in Montréal Québec CA. 新西兰奥克兰的凌晨2点,比加尔各答的凌晨2点早几个小时,早于凌晨2点在巴黎FR,早些时候凌晨2点在加利福尼亚州蒙特利尔。

From the LocalDateTime you can extract a LocalDate or LocalTime when you again want a date-only or time-of-day-only value as requested in the Question. LocalDateTime ,当您再次想要问题中所请求的仅限日期或仅限时间的LocalTime时,您可以提取LocalDateLocalTime

LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();

ZonedDateTime

If you know the offset-from-UTC intended for this value, apply a ZoneOffset to get an OffsetDateTime . 如果您知道此值的UTC偏移量 ,请应用ZoneOffset以获取OffsetDateTime Even better, use a time zone if known, a ZonedId to get a ZonedDateTime . 更好的是,使用时区(如果已知), ZonedId可以获得ZonedDateTime

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

zdt.toString(): 2011-01-12T02:00:00-05:00[America/Montreal] zdt.toString():2011-01-12T02:00:00-05:00 [美国/蒙特利尔]

From the ZonedDateTime you can extract a LocalDate or LocalTime when you again want a date-only or time-of-day-only value as requested in the Question. ZonedDateTime ,当您再次想要问题中所请求的仅限日期或仅限时间的LocalTime时,您可以提取LocalDateZonedDateTime

LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();

Conversion 转变

Best to avoid java.util.Date like the Plague. 最好避免像瘟疫这样的java.util.Date But if you must to work with old code not yet updated to java.time types, you can convert to/from java.time by calling new methods added to the old classes. 但是,如果必须使用尚未更新为java.time类型的旧代码,则可以通过调用添加到旧类的新方法来转换为/从java.time转换。 From a ZonedDateTime you can extract an java.time.Instant (a moment on the timeline in UTC) and feed that to a static method on Date . ZonedDateTime您可以提取java.time.Instant (UTC时间轴上的时刻)并将其提供给Date上的静态方法。

java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );

For more conversion info, see Convert java.util.Date to what “java.time” type? 有关更多转换信息,请参阅将java.util.Date转换为“java.time”类型? .

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . 这些类取代了麻烦的旧日期时间类,如java.util.Date.Calendarjava.text.SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to java.time. 现在处于维护模式Joda-Time项目建议迁移到java.time。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use… ). 大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植 ,并进一步适应的AndroidThreeTenABP (见如何使用...... )。

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM