Java 当使用介于、和12小时不工作的时间时,Joda时间不考虑上午/下午
我正在编写一个程序,使用Joda Time计算java中的年龄差异,在计算小时间隔时,它不考虑am和PM。这是我的密码:Java 当使用介于、和12小时不工作的时间时,Joda时间不考虑上午/下午,java,eclipse,datetime,jodatime,Java,Eclipse,Datetime,Jodatime,我正在编写一个程序,使用Joda Time计算java中的年龄差异,在计算小时间隔时,它不考虑am和PM。这是我的密码: public static void main(String[] args) { Scanner scan = new Scanner(System.in); String DOB = ""; String NOW = ""; SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String DOB = "";
String NOW = "";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date dob = null;
Date now = null;
try {
System.out
.println("Enter the date and time of your birth using the mm/dd/yyyy and the hh:mm AM/PM format: ");
DOB = scan.nextLine();
System.out
.println("Enter the date and time using the mm/dd/yyyy and the hh:mm AM/PM format: ");
NOW = scan.nextLine();
dob = format.parse(DOB);
now = format.parse(NOW);
DateTime dob1 = new DateTime(dob);
DateTime now1 = new DateTime(now);
System.out.print("You are ");
System.out.print(Years.yearsBetween(dob1, now1).getYears()
+ " years, ");
System.out.print(Months.monthsBetween(dob1, now1).getMonths() % 12
+ " months, ");
System.out.print(Days.daysBetween(dob1, now1).getDays() % 60
+ " days, ");
System.out.print(Hours.hoursBetween(dob1, now1).getHours() % 12
+ " hours, ");
System.out.print("and "
+ Minutes.minutesBetween(dob1, now1).getMinutes() % 60
+ " minutes old!");
} catch (Exception e) {
e.printStackTrace();
}
}}
如果我对出生日期的输入是2014年1月1日凌晨12:00,而我对当前时间的输入是2014年1月1日下午12:00,则结果是:您的年龄为0岁、0个月、0小时、0分钟。当它应该是12小时大的时候。有办法解决这个问题吗?我猜有一些方法可以实现halfdayOfDay方法并在我的DateTime上调用它,但我还没有找到它…谢谢你的帮助!顺便说一句,我使用12小时的输入,但在解析时它仍然接受13:00,而在12:00时它应该最大 你在做模12运算,计算时间间隔
Hours.hoursBetween(dob1, now1).getHours() % 12
所以
你工作太辛苦了 Joda Time提供的课程正好可以完成这项工作:和 看 该答案显示的代码如下所示:
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix(" seconds ago\n")
.appendMinutes().appendSuffix(" minutes ago\n")
.appendHours().appendSuffix(" hours ago\n")
.appendDays().appendSuffix(" days ago\n")
.appendWeeks().appendSuffix(" weeks ago\n")
.appendMonths().appendSuffix(" months ago\n")
.appendYears().appendSuffix(" years ago\n")
.printZeroNever()
.toFormatter();
为什么要使用SimpleDataFormat而不是Joda的内置DateTimeFormat?我是Joda的新手,不知道如何使用它。那么我该如何解决这个问题呢?@user2756173你想用模做什么?谢谢你,我使用它是为了让它在数月和数年之间(例如1年或12个月)不会冗余!不知道这对程序有何影响,但您知道如何避免允许用户允许超过12:00?感谢you@user2756173据我所知,没有这样的内置功能。
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix(" seconds ago\n")
.appendMinutes().appendSuffix(" minutes ago\n")
.appendHours().appendSuffix(" hours ago\n")
.appendDays().appendSuffix(" days ago\n")
.appendWeeks().appendSuffix(" weeks ago\n")
.appendMonths().appendSuffix(" months ago\n")
.appendYears().appendSuffix(" years ago\n")
.printZeroNever()
.toFormatter();