I'm trying to compare two dates using getTime() method but first date is always inferior to the second. After debugging, I figured that the first date (endTime) is taking 31-12-1969 07:00:00 instead of 01-01-1970 07:00:00. This is the code snippet:
if (endTime.before(currentTime)) {
// action
}
Note: I tried it on a different Timezone (UTC) and it worked perfectly the endTime = 01-01-1970 07:00:00. I'm java.util.Date to initialize the endTime.
Any solutions?
Edit:
This method returns the Current Time:
public static Date getCurrentTime() {
Calendar calendar = GregorianCalendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new Time(hour, minute, second);
}
This is the initialization of endTime:
Date endTime = new Date();
A timezone can become negative. Try sth. like (pseudocode):
time = time<"01-01-1970 00:00:00" ? "01-01-1970 00:00:00" : time;
But then you compare to UTC instead of timezone. Hope this helps you.
Related
I want to calculate Relatives Date which is how many days different from 01/01/1957 to a given date. I need handle Daylight saving at the same time. Here is the code:
public String convertToRelative(String endDate) throws ParseException {
String relativeDate;
String baseDate = "19570101";
boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(baseDate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endDate));
long time2 = cal.getTimeInMillis();
if ( isDST ) {
long between_days = (time2 - time1 - 3600000)/(1000*3600*24);
int relative = Integer.parseInt(String.valueOf(between_days));
relativeDate = String.valueOf(relative + 1);
} else {
long between_days = (time2 - time1)/(1000*3600*24);
int relative = Integer.parseInt(String.valueOf(between_days));
relativeDate = String.valueOf(relative + 1);
}
return relativeDate;
}
From the code, you can see I checked if the time is in daylight saving at:
boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());
But it only gets default time from the system. My question is how can I check the given date is a daylight saving date first then do the calculation part. I'm using New Zealand time zone. Thank you.
Rather than doing the calculations manually, you should try to take advantage of the built-in API of java.time which are easy to use and take care of DST for you.
Refer : https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-
The following code should help you with calculations you are trying to do:
ZoneId auckZone = ZoneId.of("Pacific/Auckland");
LocalDateTime base = LocalDate.of(1957, 01, 01).atStartOfDay();
ZonedDateTime baseDate = base.atZone(auckZone);
ZonedDateTime endDate = LocalDate.parse(endDt, DateTimeFormatter.ofPattern("yyyyMMdd")).atStartOfDay().atZone(auckZone);
System.out.println(baseDate.until(endDate, ChronoUnit.DAYS));
I found some similar questions, such as:
How to get the timezone offset in GMT(Like GMT+7:00) from android device?
How to find out GMT offset value in android
But all these answers(+12:00) are incorrect for New Zealand Daylight Saving Time now.
When I did debug, I got this from Google Calendar event object:
"dateTime" -> "2016-11-06T10:00:00.000+13:00"
So how to get the correct offset which should be +13:00?
Thanks.
To get the current offset from UTC in milliseconds (which can vary according to DST):
return TimeZone.getDefault().getOffset(System.currentTimeMillis());
To get a RFC 822 timezone String instead, you can simply create a SimpleDateFormat instance:
return new SimpleDateFormat("Z").format(new Date());
The format is (+/-)HHMM
So, I tried to get gmt offset through Calendar and SimpleDateFormat but both returns 0. I found the solution using deprecated methods in Date class.
So, this code works for me.
private double getOffset() {
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
int defHour = calendar.get(Calendar.HOUR_OF_DAY);
int defMinute = calendar.get(Calendar.MINUTE) + (defHour * 60);
Date date = new Date(System.currentTimeMillis());
int curHour = date.getHours();
int curMinute = date.getMinutes() + (curHour * 60);
double offset = ((double) curMinute - defMinute) / 60;
return offset > 12? -24 + offset : offset;
}
Then you can format a result
This code return me GMT offset.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: +0530
I am writing an app scenario, where need to match between two date if there are same or not and that I am trying to achieve using Date.compareTo(). But it never return 0 as API said for equal date.
I am getting these dates from Caledar.getTime() but it never
I checked with print to both date object and even they are returning same string.
Sat Nov 15 14:17:41 GMT+05:30 2014, Sat Nov 15 14:17:41 GMT+05:30 2014
Any suggestion, how to check date object if they are equal or not.
I think you forgot to check if the dates milliseconds are the same.
This is the source code of the compareTo method.
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
As you can see this method compares two dates using milliseconds as "time step".
Code for old API:
This code checks if two days are the same. (Without hours, minutes, seconds and milliseconds)
Date date1; //Your initial date
Date date2; //Your initial second date
//Remove hours, minutes, seconds and milliseconds by creating new "clean" Date objects
Date compare1 = new Date(date1.getYear(), date1.getMonth(), date1.getDay());
Date compare2 = new Date(date2.getYear(), date2.getMonth(), date2.getDay());
if(compare1.compareTo(compare2) == 0){
}
But I suggest you don't use Date for this task. Because the getYear, getMonth etc. methods are deprecated I suggest you take a look at newer API's like GregorianCalendar and Calendar
Code for new API
This code checks if two days are the same including hours and minutes. But without seconds and milliseconds.
Date date1;
Date date2;
Calendar compareCalendar1 = Calendar.getInstance();
Calendar compareCalendar2 = Calendar.getInstance();
compareCalendar1.setTime(date1);
compareCalendar2.setTime(date2);
//Set for both calendars the seconds and milliseconds to 0
compareCalendar1.set(Calendar.MILLISECOND, 0);
compareCalendar1.set(Calendar.SECOND, 0);
compareCalendar2.set(Calendar.MILLISECOND, 0);
compareCalendar2.set(Calendar.SECOND, 0);
if(compareCalendar1.compareTo(compareCalendar2) == 0){
}
Try to understand compare scenario :
Date date1 = Calendar.getInstance().getTime();
Date date2 = Calendar.getInstance().getTime();
date1.compareTo(date2) >> -1
AND
Date date3 = Calendar.getInstance().getTime();
Date date4 = date3;
date3.compareTo(date4) >> 0
How to get the number of milliseconds from October 15th 2011 1:52:34 P.M.
I can get the number of milliseconds from the current time.
Date date = new Date();
long currentTime = date.getTime();
System.out.println("Current time in long: " + currentTime);
long now = System.currentTimeMillis(); // Simpler way to get current time
Date date = new SimpleDateFormat("dd yyyy h:mm:ss a").parse("15 2011 1:52:34 PM");
long timeElapsed = now - date.getTime(); // Here's your number of ms
Use the Calendar API. Then set the month, date and the time you want (October 15, 2011).
To get you started look into this:
Calendar c = Calendar.getInstance();
Hope this helps!
Link
import java.util.Calendar;
import java.util.Date;
public class TimeMilisecond {
public static void main(String[] argv) {
long lDateTime = new Date().getTime();
System.out.println("Date() - Time in milliseconds: " + lDateTime);
Calendar lCDateTime = Calendar.getInstance();
System.out.println("Calender - Time in milliseconds :" + lCDateTime.getTimeInMillis());
}
}
You could use SimpleDateFormat to parse an arbitrariy date and get the difference in ms.
Use java.util.Calendar and fill it with your date information. Then use java.util.Calendar.getTimeInMillis() to get the number of milliseconds since epoch.
I have a problem parsing just the time string from my database
private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
And following the output:
String time = "17:17:57";
Date myParsedDate = timeFormat.parse(time); //forget the exception thing
//output of myParsedDate.toString = "Thu Jan 01 16:47:57 GMT+08:00 1970"
It seems as though theres a problem with the locale or something.. just a simple string.. Why is this so? i just want the date to be the having the time i need for my time picker.. gee..
Edit
Because i am using a static time format i decided to use my little helper method
public static Date getTimeFromTimeString(String timeString)
{
String[] splitStrings = timeString.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
timeDate.setSeconds(Integer.parseInt(splitStrings[2]));
return timeDate;
}
Thanks for the help Jon Skeet.. I believe it is the TimeZone offset that is causing this.. .. ill just stick to my little method..
The problem is you're printing out the result of Date.toString() - which always shows the results in the system time zone. That's probably not what you want.
The Date itself has no concept of a time zone - it's just an instant in time.
I would suggest you use Joda Time if at all possible. That has a LocalTime which actually represents what you're parsing here.
EDIT: Just to reiterate what's in the comment... I suspect that the time zone in your DateFormat is not the same as the time zone used by Date.toString. For simplicity, it's probably worth setting the DateFormat's time zone to UTC, and then if you want to convert to a Calendar you should set that time zone to UTC as well before calling setTime(date).
Just do this:
Calendar c = Calendar.getInstance();
c.setTime(myParsedDate);
int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);