Java – subtract 1 hour to datetime using joda time
I just want to subtract 1 hour from datetime. I try to find it on Google. I find a method called minus, which requires a copy of the date and takes a specific time here: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minus (long)
But I don't know how to use it. I can't find an example on the Internet
This is my code:
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,3);
DecimalFormat df = new DecimalFormat("00.00");
System.out.println(dateTime1);
table_4.setValueAt("",4);
table_4.setValueAt("",5);
Sample data:
dateTime1: 08:00 AM
dateTime2: 05:00 PM
The duration is 9 hours But I want 8 hours because I want to subtract lunch time from my program
I tried to use this stupid Code:
dateTime1.minus(-1)
I also try to parse string1 double, so I can subtract 1
double strindtoD = Integer.parseInt(string1);
I also try to make another datetime and usage period to get the difference between the two times
String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3,dateTime1);
Solution
Just use:
dateTime.minusHours(1)
This is documented in the API
Note that the datetime object is immutable, so a separate operation has no effect You need to assign the result of this method to a new object (or replace yourself):
dateTime = dateTime.minusHours(1);
As for how to obtain a period from the difference between two datetimes, you must first pass through an interval:
Period period = new Interval(begin,end).toPeriod();
Link to an so position and explain why there are two periods and intervals
Side note: joda time uses a lot of definitions in its API; Therefore, reading Javadoc requires not only reading the methods of a class, but also viewing the list of inherited methods of all inherited abstract classes / interfaces; For example, datetime is also a readableinstant One you're used to it, but it's a breeze
