[英]minus 1 hour to DateTime using Joda Time
我只想从DateTime
减去1小时,我尝试在Google上查找它,我发现有一个名为minus的方法需要一份日期副本并在此处采取特定的持续时间: http://www.joda。组织/乔达时间/ apidocs /组织/乔达/时间/ DateTime.html#减(长)
但我不知道如何使用它,我无法在互联网上找到一个例子。
这是我的代码:
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,这样我就可以减去它。
double strindtoD = Integer.parseInt(string1);
我还尝试制作另一个DateTime
并使用句号来获得两次的差异
String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
只需使用:
dateTime.minusHours(1)
这在API中有记录 。
请注意, DateTime
对象是不可变的 ,因此单独的操作无效。 您需要将此方法的结果分配给新对象(或替换自身):
dateTime = dateTime.minusHours(1);
至于如何从两个DateTime
之间的差异中获得一个Period
,你必须先经历一个Interval
:
Period period = new Interval(begin, end).toPeriod();
链接到SO帖子解释为什么有Period
和Interval
。
旁注:Joda Time在其API中使用了很多间接; 因此,读取Javadoc不仅需要一个人读取一个类的方法,而且还要查看所有继承的抽象类/接口的继承方法列表; 例如, DateTime
也是一个ReadableInstant
。 不过,你已经习惯了它,这是一件轻而易举的事。
如果您使用的是旧版本的org.joda.time.DateTime,则可以使用这样的减号(ReadablePeriod period)方法
Date date = LocalDate.now().minus(new Period(1, 0, 0, 0)).toDate();
其中Period接受int hours,int minutes,int seconds,int millis参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.