繁体   English   中英

我想在 java 中将字符串转换为日期

[英]I want to convert string to date in java

我有一个像"hh:mm:ss.SSSSSS"这样的String ,我想将此字符串转换为Date并且我想得到"hh:mm:ss.SS" 但是,当我编译我的代码时,它仍然会给出日月年时间和时区,例如"Thu Jan 01 10:50:55 TRT 1970" 我将下面的代码附加到文本中。

String a = "20:50:45.268743";
Date hour;
try {
    hour = new SimpleDateFormat("hh:mm:ss.SS").parse(a);
    System.out.println(hour);
} catch(ParseException e) {
    e.printStackTrace();
}

我的 output 是 hu Jan 01 20:55:13 TRT 1970 但我想得到 20:55:45.26。
有没有人可以帮助我解决这种情况?

此致

提示:您的示例String的格式为HH:mm:ss.SSSSSS而不是"hh:mm:ss.SSSSSS


如果您想专门解析和格式化一天中的时间(独立于一天/日期),请为此使用java.time.LocalTime

public static void main(String[] args) throws IOException {
    String a = "20:50:45.268743";
    // parse the String to a class representing a time of day
    LocalTime localTime = LocalTime.parse(a);
    // print it
    System.out.println(localTime);
    // or print it in a different format
    System.out.println(
            localTime.format(
                    DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH)));
    // or print it exactly as desired
    System.out.println(
            localTime.format(
                    DateTimeFormatter.ofPattern("HH:mm:ss.SS", Locale.ENGLISH)));
}

Output 是

20:50:45.268743
08:50:45 PM
20:50:45.26
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SS");
  hour = simpleDateFormat.parse(a);

  System.out.println(simpleDateFormat.format(hour));

暂无
暂无

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

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