JAVA comparing just Times (getTime function) - java

I have REPORTDATE field where I want to take the value just of the hours and minutes.
reportdate.getTime() returns this for example: 1439967368798
I want to compare if TIME from reportdate (hours and minutes) are between:
if reportdate>=06:45 and reportdate<13:45 then a=1;
if reportdate>=13:45 and reportdate<20:45 then a=2;
if reportdate>=20:45 and reportdate<06:45 then a=3;
I did not succeed to find some instructions on web.
Should I try with this by using the value that I am getting from getTime (1439967368798) or with some other method?

I assume that reportDate is an instance of Date. The getTime() function returns the underlying long of the Date, thats why you see this long number - miliseconds since January 1, 1970, 00:00:00 GMT.
What you need to do is convert the date to a calendar and then use the get() Method with the appropriate field constant.
This information is for Java 7 without any libraries. It would be wise to use a library like JodaTime or the Java8 Time API.
Here is an example how to do that.

Like this?
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
if (date.after(format.parse("06:45")) && date.before(format.parse("13:45"))) {
a=1;
}

Related

Difference between two java Dates

I mentioned that one of the method in the production project work wrong with dates, but i can't just replace it, because it is in production for a long time. I've created a new method, that works correct, but i can't figure out why the first method work wrong.
Old method (that works wrong):
public static Integer getNumberOfDays(Date startDate, Date endDate) {
TimeZone.setDefault((TimeZone.getTimeZone("Europe/Moscow")));
startDate.setHours(00);
startDate.setMinutes(00);
startDate.setSeconds(00);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(startDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
Calendar date = (Calendar) cal1.clone();
int daysBetween = 0;
while (date.before(cal2)){
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
New method:
public static Integer getNumberOfDaysSecondVersion(Date startDate, Date endDate) {
long difference = startDate.getTime() - endDate.getTime();
float daysBetween = (difference / (1000*60*60*24));
return (int) daysBetween > 0 ? (int) daysBetween : 0;
}
Here is how i call both:
DateFormat formated = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(Calculation.getNumberOfDays(
formated.parse("2018-06-14"),
formated.parse("2018-06-06")
));
System.out.println(Calculation.getNumberOfDaysSecondVersion(
format.parse("2018-06-14"),
format.parse("2018-06-06"))
);
Output:
0
8
Please help.
Your old method is the correct one. When start date is after end date, it returns 0. This is the case in your call.
Your new method subtracts end date from start date, which is wrong, is should be the other way around. I also suspect that it will give surprises across transitions from and to summer time (DST). While Moscow currently doesn’t use summer time, it has done historically, at least until 2010, and may do again if politicians decide so.
That said, you should try if you can avoid the old and long outdated date and time classes DateFormat, SimpleDateFormat, Calendar, Date and TimeZone. Today we have so much better in java.time, the modern Java date and time API. Of course, in legacy code you have old-fashioned Date objects. When writing a new method, I recommend you convert those to the modern LocalDate and use ChronoUnit.DAYS.between().
ChronoUnit.DAYS.between(
LocalDate.parse( "2018-06-14" ) ,
LocalDate.parse( "2018-06-06" )
)
-8
Be aware that when the old method sets the default time zone, it affects all programs running in your JVM and may come as a nasty surprise to other parts of your program and to other programs.
You used a very different algorithm for the two versions.
The old version keeps adding days to the start date until it is after the end date.
The new version subtracts the end date from the start date and divides it by the number of milliseconds there are in a day.
This means that for the first version to work, the start date must be before the end date, and for the second version to work, the start date must be after the end date. The parameters you gave the the first version has the start date after the end date, making it return 0.
To fix this, you can just reverse the two arguments:
System.out.println(getNumberOfDays(
formated.parse("2018-06-06"),
formated.parse("2018-06-14")
));
Or, check which date comes first before calculating the difference between them.
By the way, your first version seems to output one more than your second version. You seem to want a result of 8 days. This means that your first version has an off-by-1 error. You can fix this by subtracting 1 from the counted result.
Remember to always work with java.time whenever you can!
Probably because startDate and endDate's timezones aren't affected by setting the default timezone, so that when you set Calendar times (in Moscow time) based on them, you're converting timezones, possibly turning 00:00:00 into the previous day 21:00:00 or something.
EDIT
Seeing your outputs, it became obvious... you're passing in a start date that is in the future compared to end date. The original method uses a loop that can only count up, while your new method takes the absolute value of the difference.

How to parse a timezone into a long to store into sqlite?

so I am using nodejs to send back a json object, on return I get the following value for date "2016-05-02T04:00:00.000Z" What I need to do is store this in the sqlite db as a long on my Android app - (timezone does not matter, the only things I care about are the year,month, and day).
Now I will be getting a list of 50 objects with this date format - so it has to be efficient somewhat.
I have read that timezones are not parse-able but then people stated that in the new Java it is, so please let me know how I can go about parsing it correctly.
Is SimpleDateFormat suppose to work?
you may use Calendar class like this:
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
but before that you have to manually parse your String. Split by letter "T", then get array[0] and split by "-", then Integer.parseInt(..) to get day, month and year ints. For timestamp you may use c,getTimeInMillis();
Just simply use time in milliseconds.
In Android for getting the current time you can use System.currentTimeMillis and from that you can easily make out year, month and day.
Yes, SimpleDateFormat works.
What you need to do is parse your String timestamp into a Date object from which you could retrieve the millisecond differential since Jan. 1, 1970, midnight GMT.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = sdf.parse(timestamp);
and then you call the getTime() method to get the diffential between your timestamp and Jan. 1, 1970, midnight GMT.
d.getTime();
doc : http://developer.android.com/reference/java/text/SimpleDateFormat.html and http://developer.android.com/reference/java/util/Date.html#getTime()

Java: Compare Date.getTime with a different date [duplicate]

This question already has answers here:
How to convert date time from one time zone to another time zone
(5 answers)
Closed 7 years ago.
There is the date date1 given with the format YY-MM-dd hh:mm:ss.SSS
I want to compare
date1.getTime()
with one retrieved by doing
new Date().getTime()
There is
SimpleDateFormat sf = new SimpleDateFormat("YY-MM-dd hh:mm:ss.SSS");
Date date1 = sf.parse(date1AsString);
...
compare date1.getTime() with new Date().getTime();
How can I bring these two dates to a common 'timezone' to compare them?
How can I obtain date1 to be on the same 'time length' as new Date()? I want to have the same timezone...
Thanks
From the javadoc of Date
The class Date represents a specific instant in time, with millisecond precision.
An instance in time is agnostic of our definition of time enhanced with time zones. Right now is the same for you and me, regardless of the fact that we are (potentially) in different time zones.
What adds the notion of a time zone is the DateFormat
The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
When you invoke Date#getTime(), you get back
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
This is something you can use to compare Date objects since they have the same root. Similarly, the compareTo will return
the value 0 if the argument Date is equal to this Date; a value
less than 0 if this Date is before the Date argument; and a value
greater than 0 if this Date is after the Date argument.
You cannot compare two dates if their timezone information is unknown.
For example if your date1AsString variable is simply 2014-12-16 16:00:00 then you cannot tell if it is greater than or less than 2014-12-16 20:00:00+0000.
It looks like first date is 4 hours less than second one; but if someone adds that the first date is Pacific Time (UTC-0800) then it would actually be 4 hours more than the second date (2014-12-16 16:00:00-0800 = 2014-12-17 00:00:00+0000).
So, if date1AsString has an unknown timezone then you cannot convert it to UTC or anything else for comparison.
getTime() Returns the number of milliseconds since January 1, 1970, 00:00 :00. You will want to compare the two longs, roughly like so:
long time = new Date().getTime();
long time2 = date1.getTime();
if(time>time2)
System.out.println(String.format("time is greater than time2 by %d", time-time2)
else
System.out.println(String.format("time2 is greater than time by %d", time2-time)
if you know Timezone
date1.setTime(date1.getTime()+/-(3600000*hours)) to convert, if date1 time is GMT to go to GMT+2 hours must be 2 and sing must be +
Typically any server environment is going to be using GMT so you wont have to worry about the timezone when comparing dates, only when formatting the value to be display to users.
You can compare two dates like so:
SimpleDateFormat sf = new SimpleDateFormat("YY-MM-dd hh:mm:ss.SSS");
Date date1 = sf.parse(date1AsString);
boolean isBefore = date1.before(new Date());
boolean isAfter = date1.after(new Date());
Alternatively, you can compare the numeric values of the unix time to get the same result:
...
boolean isBefore = date1.getTime() < new Date().getTime();
boolean isAfter = date1.getTime() > new Date().getTime();
The Date Class has methods like before(date) and after(date). You should take a look into the Date Class.
So I think what you are looking for is to set the time zone of the SimpleDateFormat:
sf.setTimeZone(TimeZone.getTimeZone("EST"));

Java checking time in a timestamp

Currently I have a timestamp for example say, 2012-06-23 14:24:07.975 and
two times - 8AM and 3PM.
In java, how can I check whether the above timestamp is between the particular two time.
In other words, I need to check whether the time in timestamp (2012-06-23 14:24:07.975) falls between 8AM and 3PM or not.
Any suggestions.
You can convert the timestamp into an actual Date afterwards you convert it into a Calendar from where you can extract the hour and check it against your given hours.
Use SimpleDateFormat for getting a Date out of your Timestamp, if you cannot directly convert it.. Afterwards
Calendar cal = new GregorianCalendar();
cal.setTime(yourDate);
int hour = cal.get(Calendar.HOUR_OF_DAY);
Now do your hour check.
before and after methods should help you to do that. See docs.
I suggest using compareTo method in Date.

java - how to compare same days in date

I have a long data member that represents a date.
I cast it to a
Date d = new Date(long);
I want to now if a nother date has the same day.
How do I do it?
Thanks.
(For andrew)
Edit :
Found this solution
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));
in here
Comparing two java.util.Dates to see if they are in the same day
looks nice
use the joda api.
http://joda-time.sourceforge.net/
Its a lot easier and better than the Calendar object route in java jdk
Well you can convert them both to calendar Objects and get the calendar objects day and compare that way.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(LONG VALUE HERE);
int day = cal.get(Calendar.DAY_OF_MONTH);
Do the same thing with the other date, and compare the values.
edit: By the way, you are not casting the long to a date, you are just creating a Date object using a long.
Use apache commons.
DateUtils.isSameDay(date1, date2);
To see if the dates are equal:
date_one.equals(date_two);
To see if just the day is equal, I usually chop the time off the date (setHours(0), setMinutes(0), etc.) and then use the .equals() method.
Use java.util.Calendar for all comparison operations.

Categories

Resources