使用Joda组合两个Date实例以创建日期时间 [英] Combining two Date instance to create date-time using Joda

查看:62
本文介绍了使用Joda组合两个Date实例以创建日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 java.util.Date 实例,其中包含日期值和时间值。现在,我想结合这些值来创建表示日期和时间的单个 java.util.Date 实例。

I have two java.util.Date instances which is contain date value and time value. now I want to combine these values to create single java.util.Date instance representing the date and time.

这里有一些例子来说明我想要什么:

here some example to make clear what I'd want :

      Date date = 2015-06-01;
      Date time = 22:30;

合并为:

     Date dateTime = 2015-06-01 22:30;

我做了一些搜索,发现了这个问题
组合java.util.Dates创建日期时间
与我当前的问题类似。但是不建议使用该问题的答案。

I do some search and I found this question Combining java.util.Dates to create a date-time which is similar with my current issue. But the chosen answer on that question is deprecated.

推荐答案

使用日历,您可以在没有JODA的情况下完成

You can do it without JODA, by using Calendar

但是,当您询问JODA时,可以在JODA中进行以下操作:

However, as you asked about JODA, here is the way to do in JODA:

// you want the date part from it
Date d = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-01-02 03:04:05");

// you want to time part from it
Date t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-02-03 04:05:06");


LocalDate datePart = new LocalDate(d);
LocalTime timePart = new LocalTime(t);
LocalDateTime dateTime = datePart.toLocalDateTime(timePart);
Date result = dateTime.toDate();

// Or shrink the above 4 lines into one, as follow
// Date result = new LocalDate(d).toLocalDateTime(new LocalTime(t)).toDate();

System.out.println("result " + result);
// print out result Wed Jan 02 04:05:06 CST 2013

这篇关于使用Joda组合两个Date实例以创建日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆