Is there a way to convert a Time and Date variable to a DateTime?
I have a period between two DateTime variables, for each Date in that period I want to store a period IN that Date with a begin DateTime and end DateTime, so a day can have multiple periods defined by a DateTime.
Can't seem to figure out how to combine Date and Time to a DateTime.
Thanks in advance!
Plain java Date
and Joda-Time DateTime
should serve the purpose.
Date date = new Date(); // java.util.Date; - This date has both the date and time in it already.
DateTime dateTime = new DateTime(date);
For more info about Joda-Time.
If you have two String
objects, where 1 holds the Date
and the other Time
, you can combine the 2 Strings and use a SDF to parse it and get the Date
object, which you can then convert to DateTime
.
Fixed it using this:
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}
Even if this question is a bit older and already answered, I could not find a satisfying solution. The best method for this problem is probably the following code (without any parsing and exception handling required):
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
DateTime t = new DateTime(time);
return new DateTime(date).withTime(t.getHourOfDay(), t.getMinuteOfHour(), t.getSecondOfMinute(), t.getMillisOfSecond());
}
I am pretty sure that you can find how to construct date and time instances separately.
However on the datetime object itself you can specify the following.
dateTimeObject = dateTimeObject.withHourOfDay(12);
dateTimeObject = dateTimeObject.withMinuteofHour(59);
dateTimeObject = dateTimeObject.withSecondOfMinute(59);
Hope this helps!
DateTime dateTime = new DateTime("yyyy-MM-dd");.
System.out.println("============> " + dateTime.toString());
INPUT : 2018-01-04
OUTPUT : ============> 2018-01-05T00:00:00.000+05:30
With java.time, the modern Java date and time API, this is simple and straightforward:
LocalTime time = LocalTime.of(23, 45);
LocalDate date = LocalDate.of(2019, Month.NOVEMBER, 23);
LocalDateTime combined = date.atTime(time);
System.out.println(combined);
Output is:
2019-11-23T23:45
I know you asked about Joda-Time. However, the Joda-Time homepage says:
Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to
java.time
(JSR-310).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.