Joda: Convert Date and Time to DateTime - java

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!

java.time
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).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Joda-Time homepage

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

Related

Time interval in SimpleDateFormat [duplicate]

How can we add or subtract date in java? For instance java.sql.Date and formatted like this: yyyy-MM-dd, how can i Add 5 months from that? I've seen in some tutorial that they are using Calendar, can we set date on it? Please Help.
Example: 2012-01-01 when added 5 months will become 2012-06-01.
PS: I'm a .Net Programmer and slowly learning to Java environment.
First of all you have to convert your String date to java.util.Date, than you have to use java.util.Calendar to manipulate dates. It is also possible to do math with millis, but I do not recommend this.
public static void main( final String[] args ) throws ParseException {
final String sdate = "2012-01-01";
final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
final Date date = df.parse( sdate ); // conversion from String
final java.util.Calendar cal = GregorianCalendar.getInstance();
cal.setTime( date );
cal.add( GregorianCalendar.MONTH, 5 ); // date manipulation
System.out.println( "result: " + df.format( cal.getTime() ) ); // conversion to String
}
Stear clear of the built-in Date class for date math. Take a look at JodaTime, which has a much better API for this kind of thing.
Use Calendar
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 5);
java.time
The accepted answer uses java.util date-time API and SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
You do not need a DateTimeFormatter for your date string: java.time API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date string, 2012-01-01 which can be parsed directly into a LocalDate instance, that contains just date units.
Having parsed the date string into LocalDate, you can add or subtract different date units e.g. years, months, days etc. to it.
Demo:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String args[]) {
LocalDate date = LocalDate.parse("2012-01-01");
System.out.println(date);
LocalDate afterFiveMonths = date.plusMonths(5);
LocalDate beforeFiveMonths = date.minusMonths(5);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
// Alternatively,
afterFiveMonths = date.plus(5, ChronoUnit.MONTHS);
beforeFiveMonths = date.minus(5, ChronoUnit.MONTHS);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
}
}
Output:
2012-01-01
2012-06-01
2011-08-01
2012-06-01
2011-08-01
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
To convert a Date to a Calendar, use:
Date date = your_date_here;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Then use the calendar arithmetic functions to add/subtract:
cal.add(Calendar.MONTH, 5);
Or, Convert the date to time in milis. Do the math, and convert the millis back to a date.
use CalenderUtils from google's package GWT.
import com.google.gwt.user.datepicker.client.CalendarUtil;
...
//now
Date d = new Date();
// Now + 2 months
CalendarUtil.addMonthsToDate(d, 2);
Another option is the DateUtils class from the 3rd party Apache Commons library collection. Example:
Date d = DateUtils.parseDate("2012-01-01", "yyyy-MM-dd");
Date d2 = DateUtils.addMonths(d, 5);
System.out.println("Old date + 5 months = " + d2);
There are various ways. One of them could be with joda.time.
This does not answer the question by using Calendar but one of the other approach if needed by someone. :D
import java.sql.Date;
import org.joda.time.DateTime;
//
DateTime datetime = new DateTime("2012-01-01");
Date dt = new Date(datetime.plusMonths(5).toDate().getTime());
System.out.println(dt);
// This gives output as 2012-06-01
PS: Happy coding with Java
The complete program that does date addition is in http://dwbitechguru.blogspot.ca/2014/09/jave-program-to-add-or-substract-dates.html

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

I have an external API that returns me dates as longs, represented as milliseconds since the beginning of the Epoch.
With the old style Java API, I would simply construct a Date from it with
Date myDate = new Date(startDateLong)
What is the equivalent in Java 8's LocalDate/LocalDateTime classes?
I am interested in converting the point in time represented by the long to a LocalDate in my current local timezone.
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use Instant.ofEpochMilli(long epochMilli)
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate, unlike java.util.Date, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
Timezones and stuff aside, a very simple alternative to new Date(startDateLong) could be LocalDate.ofEpochDay(startDateLong / 86400000L)
A simple version based on #Michael Piefel answer:
LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(epochMillis).toDays());
replace now.getTime() with your long value.
//GET UTC time for current date
Date now= new Date();
//LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
I have tested this alternative solution for LocalDateTime:
public static LocalDateTime increaseByMillis(final LocalDateTime ldt, final long millis)
{
return LocalDateTime.ofInstant(Instant.ofEpochMilli(ldt.toInstant(ZoneOffset.UTC).toEpochMilli()+millis), ZoneId.of(ZoneOffset.UTC.getId()));
}
Test:
LocalDateTime test = LocalDateTime.now();
LocalDateTime increased = MyUtilsAbc.increaseByMillis(test, 1000);
Assert.assertEquals("Increase of LocalDateTime not working (anymore)!", test.toEpochSecond(ZoneOffset.UTC) +1, increased.toEpochSecond(ZoneOffset.UTC));
In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:
long startDateLong = <...>
LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Addition and Subtraction of Dates in Java

How can we add or subtract date in java? For instance java.sql.Date and formatted like this: yyyy-MM-dd, how can i Add 5 months from that? I've seen in some tutorial that they are using Calendar, can we set date on it? Please Help.
Example: 2012-01-01 when added 5 months will become 2012-06-01.
PS: I'm a .Net Programmer and slowly learning to Java environment.
First of all you have to convert your String date to java.util.Date, than you have to use java.util.Calendar to manipulate dates. It is also possible to do math with millis, but I do not recommend this.
public static void main( final String[] args ) throws ParseException {
final String sdate = "2012-01-01";
final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
final Date date = df.parse( sdate ); // conversion from String
final java.util.Calendar cal = GregorianCalendar.getInstance();
cal.setTime( date );
cal.add( GregorianCalendar.MONTH, 5 ); // date manipulation
System.out.println( "result: " + df.format( cal.getTime() ) ); // conversion to String
}
Stear clear of the built-in Date class for date math. Take a look at JodaTime, which has a much better API for this kind of thing.
Use Calendar
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 5);
java.time
The accepted answer uses java.util date-time API and SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
You do not need a DateTimeFormatter for your date string: java.time API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date string, 2012-01-01 which can be parsed directly into a LocalDate instance, that contains just date units.
Having parsed the date string into LocalDate, you can add or subtract different date units e.g. years, months, days etc. to it.
Demo:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String args[]) {
LocalDate date = LocalDate.parse("2012-01-01");
System.out.println(date);
LocalDate afterFiveMonths = date.plusMonths(5);
LocalDate beforeFiveMonths = date.minusMonths(5);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
// Alternatively,
afterFiveMonths = date.plus(5, ChronoUnit.MONTHS);
beforeFiveMonths = date.minus(5, ChronoUnit.MONTHS);
System.out.println(afterFiveMonths);
System.out.println(beforeFiveMonths);
}
}
Output:
2012-01-01
2012-06-01
2011-08-01
2012-06-01
2011-08-01
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
To convert a Date to a Calendar, use:
Date date = your_date_here;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Then use the calendar arithmetic functions to add/subtract:
cal.add(Calendar.MONTH, 5);
Or, Convert the date to time in milis. Do the math, and convert the millis back to a date.
use CalenderUtils from google's package GWT.
import com.google.gwt.user.datepicker.client.CalendarUtil;
...
//now
Date d = new Date();
// Now + 2 months
CalendarUtil.addMonthsToDate(d, 2);
Another option is the DateUtils class from the 3rd party Apache Commons library collection. Example:
Date d = DateUtils.parseDate("2012-01-01", "yyyy-MM-dd");
Date d2 = DateUtils.addMonths(d, 5);
System.out.println("Old date + 5 months = " + d2);
There are various ways. One of them could be with joda.time.
This does not answer the question by using Calendar but one of the other approach if needed by someone. :D
import java.sql.Date;
import org.joda.time.DateTime;
//
DateTime datetime = new DateTime("2012-01-01");
Date dt = new Date(datetime.plusMonths(5).toDate().getTime());
System.out.println(dt);
// This gives output as 2012-06-01
PS: Happy coding with Java
The complete program that does date addition is in http://dwbitechguru.blogspot.ca/2014/09/jave-program-to-add-or-substract-dates.html

convert String in time to Time object without Date

i got problem to convert String time to Time object because it print together with Date. this is my code.
String time = "15:30:18";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
System.out.println("Time: " + date);
how to convert and print Time only without Date in java. it will be better if you could give an example.
thank you.
Use the same SimpleDateFormat that you used to parse it:
String time = "15:30:18";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
Remember, the Date object always represents a combined date/time value. It can't properly represent a date-only or time-only value, so you have to use the correct DateFormat to ensure you only "see" the parts that you want.
This works as well
String t = "00:00:00"
Time.valueOf(t);
Joda-Time | java.time
If you want a time-only value without a date and without a time zone, then you must use either the Joda-Time library or the new java.time package bundled in Java 8 (inspired by Joda-Time).
Both of those frameworks offers a LocalTime class.
In Joda-Time 2.4…
LocalTime localTime = new LocalTime( "15:30:18" );
In java.time…
LocalTime localTime = LocalTime.parse( "15:30:18" );

Categories

Resources