java/android datetime timespan - java

If i have a simpledateformat object:
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
And have two times, 12:12 and 13:13 for example, is there an easy way to check if the current time is between the two SimpleDateFormats (The clock is 12:15 for example)? Thanks

DateFormat newDateFormat = new SimpleDateFormat("HH:mm");
Date d1 = newDateFormat.parse("12:12");
Date d2 = newDateFormat.parse("13:13");
Date myDate = newDateFormat.parse("12:15");
if(myDate.getTime() >= d1.getTime() && myDate.getTime() <= d2.getTime()){
//yes it is in between including border
}

Compare them using Date or Calendar objects, SimpleDateFormat is just a representation. You can use format.parse("12:12") and ir returns a Date object representing that time.

If anyone is looking for a better and lighter library to use in Android/ Java that handles interval better, you can use a library that a wrote to use in my own Android app. https://github.com/ashokgelal/samaya
Also, see this question: Do we have a TimeSpan sort of class in Java

Related

What's wrong with time subtraction?

I know that Date class can be really painful at times.
Could you please give me some painkillers in the form of the piece of advice on how to subtract time?
What I have is:
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
String s = "13.04.2015 16:00";
String s2 = "13.04.2015 15:30";
Date date = format.parse(s);
System.out.println(timeFormat.format(date.getTime() - format.parse(s2).getTime()));
This gives me 02:30:00, but I'd love to get 00:30:00 :)
I suggest to force common TimeZone for both SimpleDateFormat:
format.setTimeZone(TimeZone.getTimeZone("UTC"));
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
before formatting date.
I'm not sure if you are stuck to Java Date class by some requirements, but if you are working with date and time a lot in your application I recommend Joda-Time library. It solves many problems out of the box and allows executing operations on date and time in easier way.

Iterate through date ranges without using libraries - Java

Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks
String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
doSomethingWithTheCalendar(calendar);
calendar.add(Calendar.DATE, 1);
}
Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.
Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.
See the API documentation of the classes mentioned above.
Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).

Java How to create a UTC and add few ms to the same UTC object

static String createUTCTime()
{
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
cal.add(Calendar.SECOND, 10);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setCalendar(cal);
return f.format(new Date());
}
essentially what I would like to do below
Calendar objectX = createUTCTime();
//2012-Nov-27 18:35:40
x.addMS(10);
//2012-Nov-27 18:35:50
How do you handle UTC times to manipulate them?
Date is just a point in time, it doesn't hold any time zone information. If you want to work with time zones and dates, you need Calendar:
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
cal.add(Calendar.SECONDS, 10);
Now the tricky part, you cannot just convert it to Date (cal.getTime()) as it will loose time zone (but will still represent the same point-in-time). What you should do is create a SimpleDateFormat` configured to use UTC.
On the other hand if you only need seconds or milliseconds, Date is fine. Just remember to format it in correct time zone. But you shouldn't use Date for hours and everything above (assumption that hour is 3600000 milliseconds is sometimes wrong due to leap seconds, DST, etc.)
It's really unclear what you're trying to do - but if you're trying to create an object to work with further, you shouldn't be converting it into a string representation, which is what SimpleDateFormat.format does.
The Java API for working with dates and times is pretty broken, to be honest - you'd be much better off with Joda Time. For example:
DateTime x = new DateTime(DateTimeZone.UTC);
x = x.plusMillis(10);
Joda Time provides plenty of immutable types for dates and times, which are significantly better for readability than the mutable Calendar and Date types. Additionally, it supports a lot more types to represent different kinds of values.
Really, avoid java.util.Date/Calendar like the plague :)
You can use following code.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.add(Calendar.MILLISECOND, 10);
DateFormat df = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(cal.getTimeZone());
System.out.println(f.format(cal.getTime()));
getTime provide Date object which do not have any information about timeZone. By Date object can display the date in GMT(toGMTString()) and local time zone(toLocalString()).
This code will provide you time in UTC, in the required format.

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.

What's the most efficient way to strip out the time from a Java Date object?

What's the most efficient way to remove the time portion from a Java date object using only Classes from within the JDK?
I have the following
myObject.getDate() =
{java.util.Date}"Wed May 26 23:59:00
BST 2010"
To reset the time back to 00:00:00, I'm doing the following
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse(sdf.format(myObject.getDate()));
The output is now
myDate = {java.util.Date}"Wed May 26
00:00:00 BST 2010"
Is there a better way to achieve the same result?
More verbose, but probably more efficient:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(date);
// cal.set(Calendar.HOUR, 0); // As jarnbjo pointed out this isn't enough
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Also, you don't need to worry about locale settings, which may cause problems with string to date conversions.
If you have Apache commons, you can use DateUtils.truncate():
Date myDate = DateUtils.truncate(myObject.getDate(), Calendar.DATE)
(If you don't have access to Apache Commons, DateUtils.truncate() is implemented basically the same as kgiannakakis's answer.)
Now, if you want "clever" code that is very fast, and you don't mind using deprecated functions from java.util.Date, here is another solution. (Disclaimer: I wouldn't use this code myself. But I have tested it and it works, even on days when DST starts/ends.)
long ts = myObject.getDate().getTime() - myObject.getDate().getTimezoneOffset()*60000L;
Date myDate = new Date(ts - ts % (3600000L*24L));
myDate.setTime(myDate.getTime() + myDate.getTimezoneOffset()*60000L);
These methods are deprecated, but given a Date, you can do something like this:
Date d = ...;
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
You should use a Calendar if possible. You'd then use the cal.set(Calendar.MINUTE, 0), etc.
It should be mentioned that if it's at all an option, you should use Joda-Time.
Related questions
Why were most java.util.Date methods deprecated?
Are you taking time zone into consideration? I see you have BST right now, but what when BST is over? Do you still wish to use BST?
Anyway, I'd suggest you have a look at DateMidnight from JodaTime and use that.
Things may vary depending on how you want to handle the time zones. But in it's simplest form, it should be as simple as:
DateMidnight d = new DateMidnight(myObject.getDate());
If you must convert back go java.util.Date:
Date myDate = d.toDate();
myDate.setTime(myDate.getTime()-myDate.getTime()%86400000)
might do the trick. Talk about quick&dirty.

Categories

Resources