17

我只想从DateTime我尝试在 Google 上查找它的时间中减去 1 小时,我发现有一种名为减号的方法可以获取日期的副本并在此处获取特定的持续时间: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);

样本数据:

    dateTime1: 08:00 AM
    dateTime2: 05:00 PM

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

我用这个愚蠢的代码试了一下:

dateTime1.minus(-1) 

我还尝试将解析string1加倍,以便可以将其减一。

double strindtoD = Integer.parseInt(string1);

我还尝试制作另一个DateTime并使用 period 来获得两个时间的差异

String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
4

3 回答 3

43

只需使用:

dateTime.minusHours(1)

记录在 API 中

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

dateTime = dateTime.minusHours(1);

至于如何Period从两个DateTimes的差中得到a,首先要经过一个Interval

Period period = new Interval(begin, end).toPeriod();

链接到一个 SO 帖子,解释为什么同时存在PeriodInterval

旁注:Joda Time 在其 API 中使用了很多间接方法;因此,阅读 Javadoc 不仅需要阅读一个类的方法,还需要查看所有继承的抽象类/接口的继​​承方法列表;例如, aDateTime也是 a ReadableInstant。不过,一旦你习惯了它,它就会变得轻而易举。

于 2013-06-08T14:17:17.667 回答
0

如果您使用的是 org.joda.time.DateTime 的旧版本,那么您可以像这样使用 minus(ReadablePeriod period) 方法

        Date date = LocalDate.now().minus(new Period(1, 0, 0, 0)).toDate();

其中 Period 接受 int hours, int minutes, int seconds, int millis 参数

于 2016-01-20T06:13:08.990 回答
-1

通过使用 Calender 类对象,您可以使用此方法减去小时数。

cal.add(Calendar.HOUR_OF_DAY, -numberOfHours);

这也是完整的示例链接

于 2013-11-12T09:11:16.833 回答