简体   繁体   English

如何在 -01:-05:00 到 -01:05:00 中制作时间格式

[英]how to make a time format in -01:-05:00 to -01:05:00

After subtracting time 1:10 and 2:15 using java I am getting the ouput as long which is in milliseconds -3900000.使用 java 减去时间 1:10 和 2:15 后,我得到了以毫秒为单位的输出 -3900000。 Then I convert this millisecond into time format, then the output produced is Output : -01:-05:00.然后我将这个毫秒转换成时间格式,那么产生的输出是 Output :-01:-05:00。

The output I am expecting is like -01:05:00.我期待的输出就像 -01:05:00。 There should be only one negative sign in the output输出中应该只有一个负号

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

public class TimeAddition {
    public static void main(String args[]) throws ParseException {
        String b = "1:10";
        String a = "2:15";

     // converting String time into dateTime   
        DateFormat sdf = new SimpleDateFormat("hh:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date bTime = sdf.parse(b);
        Date aTime = sdf.parse(a);

        long totalTime = bTime.getTime() - aTime.getTime();

        System.out.println("Total time in millisecond = " + totalTime);

        long millis = totalTime;

        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis)
                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis)
                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

        System.out.println("Time format " + hms);   
    }

}

Output produced : Total time in millisecond = -3900000 Time format -1:-5:00产生的输出:以毫秒为单位的总时间 = -3900000 时间格式 -1:-5:00

Expected Time format = -01:05:00预期时间格式 = -01:05:00

You should do something like that:你应该做这样的事情:

  • you compute if you should add a sign (-) or not.您计算是否应该添加符号 (-)。
  • if the amount of time is negative, you get its absolute value (you can also use Maths.abs ).如果时间量是负数,你会得到它的绝对值(你也可以使用Maths.abs )。
  • you format it with the sign before.你用之前的符号格式化它。

Which gives:这使:

String sign = totalTime < 0 ? "-":"";
long millis = totalTime < 0 ? -totalTime:totalTime;
String hms = String.format("%s%02d:%02d:%02d", sign, TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis)
                       - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

Just Change this code :只需更改此代码:

TimeUnit.MILLISECONDS.toMinutes(millis)
                - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))

to this code:到这个代码:

TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)) - TimeUnit.MILLISECONDS.toMinutes(millis)

测试成功

You can use this approach as well to get time difference easily.您也可以使用这种方法轻松获得时差。

public static void main(String[] args)
{
     String time1 = "01:10:00";
     String time2 = "02:15:00";
     String finalDiff;

     try{
          SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
          Date date1 = format.parse(time1);
          Date date2 = format.parse(time2);

          long difference = date1.getTime() - date2.getTime();
          Date d;

          if(difference<0) {
              d = new Date(-1*difference);
              finalDiff = "-"+ format.format(d);
          }
          else{
              d = new Date(difference);
              finalDiff = format.format(d);
          }

          System.out.println(finalDiff);// gives the difference as required by you.

     }catch(Exception e){}
} 

Date and SimpleDateFormat are both oldfashioned and unsuited for the purpose. DateSimpleDateFormat都是老式的,不适合这个目的。 They were intended for a point in time and its representation in a certain timezone, never for the length of a time interval.它们旨在用于某个时间点及其在某个时区中的表示,而不是用于时间间隔的长度。 I would not be comfortable using them for the latter, or I would at the very least test thoroughly on computers running different time zones.我不会为后者使用它们感到舒服,或者我至少会在运行不同时区的计算机上进行彻底的测试。

My suggestion is to use the new java.time package.我的建议是使用新的java.time包。 Despite the fact discussed in the comments to this answer that it does not include a duration formatter.尽管在对此答案的评论中讨论了它不包含持续时间格式化程序的事实。

    String b = "1:10";
    String a = "2:15";

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm", Locale.ROOT);
    LocalTime end = LocalTime.parse(b, dtf);
    LocalTime start = LocalTime.parse(a, dtf);
    Duration totalTime = Duration.between(start, end);
    String sign;
    if (totalTime.isNegative()) {
        totalTime = totalTime.negated();
        sign = "-";
    } else {
        sign = "";
    }
    long hours = totalTime.toHours();
    totalTime = totalTime.minusHours(hours);
    long minutes = totalTime.toMinutes();
    totalTime = totalTime.minusMinutes(minutes);
    long seconds = totalTime.getSeconds();
    System.out.format("%s%d:%02d:%02d%n", sign, hours, minutes, seconds);

This prints:这打印:

-1:05:00

The price is we need to handle a negative interval explicitly.代价是我们需要明确处理负区间。 The good news is the library classes do all calculations for us: calculating the length of time and conversion to hours, minutes and seconds.好消息是库类为我们完成所有计算:计算时间长度并转换为小时、分钟和秒。

暂无
暂无

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

相关问题 如何将“ 2019-04-11T05:00:54.000 + 01:00”转换为dd / MM / yyyy hh:mm格式 - How to convert “2019-04-11T05:00:54.000+01:00” into dd/MM/yyyy hh:mm format java:如何将日期从“ 2014年5月1日星期四00:00:00西部”投射到“ 2014-01-05 00:00:00.0” - java : How can I cast Date from “Thu May 01 00:00:00 WEST 2014 ” to “2014-01-05 00:00:00.0” 使用 Instant.parse 解析 2018-05-01T00:00:00 日期时出错 - Error while parsing 2018-05-01T00:00:00 date using Instant.parse JMeter:Sampler结果显示“ Sample Start:1970-01-01 05:30:00 IST” - JMeter: Sampler results shows “Sample Start: 1970-01-01 05:30:00 IST” 在Android中将字符串转换为日期“ 2016-01-28T12:08:47.676706-05:00” - Convert String to Date “2016-01-28T12:08:47.676706-05:00” in android 如何使我的时钟像这样03:05:01 - How to make my clock like this 03:05:01 将字符串解析为时间使得01:00:00 - Parsing String to Time makes 01:00:00 如何以 2019-12-29 05:59:59.9999990 +00:00 格式将一天结束作为 OffsetDateTime? - How to get the end of day as a OffsetDateTime in the format 2019-12-29 05:59:59.9999990 +00:00? 如何获取此字符串的 08:00 2015-01-01T08:00:00-02:00 - How to get 08:00 of this String 2015-01-01T08:00:00-02:00 如何格式化此日期“ 2018-08-02T00:00:00 + 05:30”字符串为此“ 2018-18-02” - How to Format this Date “2018-08-02T00:00:00+05:30” String to this “2018-18-02”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM