使用Joda Time减去1小时到DateTime

Mag*_*uzu 15 java swing datetime jodatime

我只想减去DateTime我尝试在Google上查找的1小时,我发现有一个名为minus的方法需要一份日期副本并在此处采取特定的持续时间:http://www.joda.org /joda-time/apidocs/org/joda/time/DateTime.html#minus(long)

但我不知道如何使用它,我无法在互联网上找到一个例子.

这是我的代码:

String string1 = (String) table_4.getValueAt(0, 1);
    String string2= (String) table_4.getValueAt(0, 2);

    DateTimeFormatter dtf = DateTimeFormat.forPattern("hh:mm a").withLocale(Locale.ENGLISH);
    DateTime dateTime1 = dtf.parseDateTime(string1.toString());
    DateTime dateTime2 = dtf.parseDateTime(string2.toString());

    final String oldf = ("hh:mm a");
    final String newf= ("hh.mm 0");
    final String newf2= ("hh.mm a");
    final String elapsedformat = ("hh.mm");

    SimpleDateFormat format2 = new SimpleDateFormat(oldf);
    SimpleDateFormat format2E = new SimpleDateFormat(newf); 

    Period timePeriod = new Period(dateTime1, dateTime2);

    PeriodFormatter formatter = new PeriodFormatterBuilder()

     .appendHours().appendSuffix(".")
     .appendMinutes().appendSuffix("")
     .toFormatter();

    String elapsed = formatter.print(timePeriod);

    table_4.setValueAt(elapsed,0,3);

    DecimalFormat df = new DecimalFormat("00.00");
    System.out.println(dateTime1);
    table_4.setValueAt("", 0, 4);
    table_4.setValueAt("", 0, 5);
Run Code Online (Sandbox Code Playgroud)

样本数据:

    dateTime1: 08:00 AM
    dateTime2: 05:00 PM
Run Code Online (Sandbox Code Playgroud)

期限为9小时.但我希望它只是8小时,因为我想在我的程序中减去午休时间.

我试着用这个愚蠢的代码:

dateTime1.minus(-1) 
Run Code Online (Sandbox Code Playgroud)

我也试过解析string1加倍,所以我可以减去一个.

double strindtoD = Integer.parseInt(string1);
Run Code Online (Sandbox Code Playgroud)

我也尝试制作另一个DateTime并使用句号来获得两次的差异

String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 39

只需使用:

dateTime.minusHours(1)
Run Code Online (Sandbox Code Playgroud)

在API中有记录.

请注意,DateTime对象是不可变的,因此单独的操作无效.您需要将此方法的结果分配给新对象(或替换自身):

dateTime = dateTime.minusHours(1);
Run Code Online (Sandbox Code Playgroud)

至于如何获得Period两个DateTimes 之间的差异,你必须首先通过Interval:

Period period = new Interval(begin, end).toPeriod();
Run Code Online (Sandbox Code Playgroud)

链接到SO帖子解释为什么有PeriodInterval.

旁注:Joda Time在其API中使用了很多间接; 因此,读取Javadoc不仅需要一个人读取一个类的方法,而且还要查看所有继承的抽象类/接口中的继承方法列表; 例如,a DateTime也是一个ReadableInstant.不过,你已经习惯了它,这是一件轻而易举的事.