I need to compare whether a DateTime object is greater/less than 9AM PST using JodaTime library in Android.
I am getting the DateTime object in PST like this:
DateTime dt = new DateTime(DateTimeZone.forID( "America/Los_Angeles" ));
How can I compare whether the time recorded for this object is greater/less than 9AM PST?
Thanks.
You can use one of the next ways to do what you want.
1) Create a DateTime with the TimeZone and the hour that you want.
DateTime dt = new DateTime()
.withHourOfDay(9)
.withZone(DateTimeZone.forID("America/Los_Angeles"));
And then compare dt with the DateTime that you receive, create, etc.
dt.isAfter(date) or dt.isBefore(date)
2) You can set the TimeZone that you want to a copy of the DateTime that you receive.
I say copy because DateTime object is immutable. You can not modify the DateTime which you receive but create one from it, yes. You can read more about that here: Why are Joda objects immutable?
datePST = date.withZone(DateTimeZone.forID("America/Los_Angeles"));
int hour = datePST.getHourOfDay()
Now you just need to check if hour is < or > than 9.
Related
I'm trying to convert a java.time.LocalTime object to java.util.Date but can't find any suitable method. What's the correct way to do this?
Is there any reason why java doesn't seem to ship with a built-in direct conversion method?
To possible duplicates:
How to convert joda time - Doesn't work for me, probably I'm missing some "joda" libraries?
How to convert Date to LocalTime? - This adresses conversion the other way around.
LocalTime actually can't be converted to a Date, because it only contains the time part of DateTime. Like 11:00. But no day is known. You have to supply it manually:
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
Here's a blog post which explains all the conversions between the new and the old API.
There's no simple built-in conversion method, because these APIs approach the idea of date and time in completely different way.
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
From :
http://blog.progs.be/542/date-to-java-time
I added the data (hour, minute, second) one by one (from localtime to date):
reta.setHours(vol.getRetard().getHour());
reta.setMinutes(vol.getRetard().getMinute());
reta.setSeconds(vol.getRetard().getSecond());
Note :
reta: Date veriabble ;
vol.getRetard (): localtime variable
As others have said, it’s a problematic question in that a LocalTime and a Date really represent quite different and almost unrelated concepts. A LocalTime is a time of day without time zone, such as 19:45 (or 7:45 PM). A Date is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones.
I believe that the conventional way of misusing (indeed) a Date for an hour of day is setting it to that time of day on January 1, 1970 in the default time zone of the JVM. This practice carries all of the liabilities already mentioned. In particular the JVM default time zone setting can be changed at any time from another part of your program or any other program running in the same JVM. This means that a completely unrelated program may suddenly cause your Date to indicate a different time of day than the one you had initialized it to.
There’s nothing better we can do, so here goes:
LocalTime time = LocalTime.of(11, 0);
Instant timeOnEpochDayInDefaultTimeZone = LocalDate.EPOCH
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant();
Date oldfashionedDateObject = Date.from(timeOnEpochDayInDefaultTimeZone);
System.out.println(oldfashionedDateObject);
In my time zone output from this snippet is:
Thu Jan 01 11:00:00 CET 1970
Here is another approach:
We can add a LocalDate to the LocalTime in order to make it a LocalDateTime and then convert it to Date using the valueOf method of java.sql.Timestamp like this:
LocalTime localTime = LocalTime.now();
Date date = java.sql.Timestamp.valueOf(localTime.atDate(LocalDate.now()));
As #Dariusz said, we cannot convert LocalTime to Date directly as it contains only time part but Date must contain all the value along with the timeZone.
In order to get the date part, we can use LocalDate.now(). It will give us LocalDate object with today's date.
Now, we have both LocalDate and LocalTime, we can now use the LocalDateTime.of(date: LocalDate, time: LocalTime) or localTime.atDate(date: LocalDate) to get the LocalDateTime object.
And now we can convert the LocalDateTime to Date using below kotlin extension function.
fun LocalDateTime.toDate(): Date {
return Date.from(this.atZone(ZoneId.systemDefault()).toInstant())
}
I have a variable of datatype DateTime (org.joda.time.DateTime). I need to update the date value of the variable without modifying the time?
Is it possible to add days to the DateTime variable without modifying time?
[Like how we do for Date (org.apache.commons.lang.time.DateUtils) variable using method DateUtils.addDays()]
Thanks,
Sasank
Have you considered using
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#withDate%28int,%20int,%20int%29
From JavaDocs
withDate
public DateTime withDate(int year, int monthOfYear, int dayOfMonth)
Returns a copy of this datetime with the specified date, retaining the time fields.
If the date is already the date passed in, then this is returned.
DateTime d = new DateTime();
DateTime fiveDaysLater = d.plusDays(5);
This adds 5 days to your time. I hope this is what you are looking for.
The same works for plusMonths and more see: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html
i have a MySQL Database which contains several timestamps e.g. startDate and endDate. Now i want the difference between the two timestamps.
(I read a lot about the advantages of joda time, but did not work with the included java implementation.)
I do not know if i understand the concepts correctly:
I need a formatter e.g. DateTimeFormatter to format the startDate string into a valid dateTime format.
//yyyy-MM-dd HH:mm:ss.m, the last .m, is for the miliseconds i got from jdbc/mysql
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.m");
String startDate = resultSet.getString("StartDateInMySQLDB");
DateTime dateTime = formatter.parseDateTime(startDate);
Now i have a DateTime object. However i need a connection to a calendar system, to e.g. calculate the time between two dates. But is not a simple time of 24h for a day (i found several solutions with joda and without a calendar). I need something like a work-time: e.g. 09:00 AM to 05:00 PM (Monday to thursday)
Therefor i thought, i need a calendar sytem, but i do not know to connect datetime and the calendar system correctly.
I want to convert a LocalTime object to a java.sql.Time object.
java.sql.Time time = new java.sql.Time(new LocalTime(1,0,0,0).getMillisOfDay());
System.out.println(time); //20:00:00
The above code, instead of creating a Time object with a value equal to 01:00:00, creates an object with a time of 20:00:00. The local time is eastern time.
What steps should I take?
Time(..) accepts a timestamp starting from 1970. So you should pass that:
new Time(new LocalTime(...).toDateTimeToday().getMillis())
I consider the currently accepted answer to be incorrect. Although java.sql.Time implies that its date fields are set to 1970-1-1, this is not true. If you use the conversion
new java.sql.Time(new LocalTime(...).toDateTimeToday().getMillis())
then the internal millesecond representation of the java.sql.Time object will reflect today's date. This leads to unexpected behavior when comparing java.sql.Time objects.
Comparisons are performed on the millisecond value, and if the underlying dates are different, the time fields are irrelevant to the comparison result
A better method, is to explicitly work with the time-fields, using the deprecated constructor and methods in java.sql.Time:
LocalTime localTime = new LocalTime(1,0,0,0);
java.sql.Time sqlTime = new java.sql.Time(localTime.getHourOfDay(), localTime.getMinuteOfHour(), localTime.getSecondOfMinute())
Similarly, in the other direction
java.sql.Time sqlTime = new java.sql.Time(1,0,0);
LocalTime localTime = new LocalTime(sqlTime.getHours(), sqlTime.getMinues(), sqlTime.getSeconds());
This seems like a hole in the Joda Time API. Right now getLocalMillis() is protected, but that's exactly the method I'd want to use.
However, if you want to avoid deprecated methods, you can figure out time on January 1, 1970:
LocalTime lt = new LocalTime(1, 23, 45, 678);
long millis = lt.toDateTimeToday().withDate(1970, 1, 1).getMillis()
java.sql.Time time = new java.sql.Time(millis);
This seems to work. Interestingly, I tried figuring out the millis by multiplying the values of the fields out. That produced the right long value, but when I passed it to the Time constructor, something weird happened with the time zone. (I think, at least. The Time value ended up five hours before the value I passed in, and I'm on Eastern Daylight Time, so I think that's what happened.)
i found another way to convert the java.time.LocalTime to java.time.LocalTime
LocalTime localTime = LocalTime.now();
Time time = Time.valueOf(localTime);
I'm new to joda-time and I didn't find anywhere examples to do some simple things.
I want to make an object where to save a time value read from a table in a database (a java.sql.Time - e.g. "18:30:00") I don't care about time zone, so I think that I need LocalDate. But the problem is that I couldn't create a LocalDate object based on that Time object.
I tried with no success LocalDate.fromDateFields(), DateTimeParser.parseInto(), DateTimeParser.parseDateTime().
EDIT:
I should have used LocalTime.
These work:
java.sql.Time time = Time.valueOf("18:30:00");
LocalTime lt1 = LocalTime.fromDateFields(time);
LocalTime lt2 = new LocalTime(time);
According to the documentation, you should be able to construct a LocalDate directly by passing it a java.util.Date as the sole constructor argument. Since a java.sql.Time extends java.util.Date, you should be able to
final LocalDate ld = new LocalDate(mySqlTime);
This works for me:
System.out.println(new LocalDate(Time.valueOf("18:30:00")));
On the other hand, it's not a meaningful thing to do, since you'll always get January 1, 1970. But I imagine you know what you're doing.