The constructor Time is deprecated - java

private static final Time BEGIN = new Time(9, 0, 0);
private static final Time END = new Time(20, 0, 0);
The constructor Time is deprecated, is there a way to fix these declarations?

You can now use as mentioned by javadocs.
Time(long time)
Constructs a Time object using a milliseconds time value.
Short search gave me this :
Calendar cal = Calendar.getInstance();
// set Date portion to January 1, 1970
cal.set( cal.YEAR, 1970 );
cal.set( cal.MONTH, cal.JANUARY );
cal.set( cal.DATE, 1 );
cal.set( cal.MILLISECOND, 0 );
java.sql.Time jsqlT =
new java.sql.Time( cal.getTime().getTime() );

Related

Calendar add method not working as expected

I want set a (Gregorian) Calendar time to start-of-day April 1, 2016. I do this by setting month, day and year, and then setting all the time fields to their minimum values, giving me:
04/01/2016 12:00:00:000
If I subtract one millisecond I expect to get the last millisecond on the previous day, but instead I get the last millisecond on the same day:
04/01/2016 11:59:59:999
(Note: I get similar results if I subtract one second, minute or hour.)
What am I missing? Sample code follows, thanks.
package com.scg.domain;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class AdHoc
{
private static final int[] UNUSED_CAL_FIELDS =
{
Calendar.HOUR,
Calendar.MINUTE,
Calendar.SECOND,
Calendar.MILLISECOND
};
public static void main(String[] args)
{
Calendar cal = getGoodDate( Calendar.APRIL, 1,2016 );
System.out.println( cal.getCalendarType() );
adjustTime( "present", cal, 0 );
adjustTime( "past", cal, -1 );
adjustTime( "future", cal, 1 );
}
private static void adjustTime( String comment, Calendar cal, int incr )
{
Calendar newCal = Calendar.getInstance();
newCal.setTime( cal.getTime() );
newCal.add( Calendar.MILLISECOND, incr );
SimpleDateFormat fmt =
new SimpleDateFormat( "MM/dd/YYYY HH:mm:ss:SSS" );
System.out.println( comment + ": " + fmt.format( newCal.getTime() ) );
}
private static Calendar getGoodDate( int month, int day, int year )
{
Calendar cal = Calendar.getInstance();
cal.set( Calendar.YEAR, year );
cal.set( Calendar.MONTH, month );
cal.set( Calendar.DAY_OF_MONTH, day );
for ( int field : UNUSED_CAL_FIELDS )
cal.set( field, cal.getMinimum( field ) );
return cal;
}
}
You've used Calendar.HOUR, which controls only the 1-12 hour, not the 0-23 hour. Because of this, even though getMinimum returns 0, it's interpreted as 12:00 in whichever of AM or PM cal already is in, which must be PM from getInstance() (returns "now"). You really have 12:00 noon (PM). When you subtract a millisecond, it's still the same day.
To set it to midnight, try Calendar.HOUR_OF_DAY, which controls the 0-23 hour.
With this change, I get the output:
gregory
present: 04/01/2016 00:00:00:000
past: 03/31/2016 23:59:59:999
future: 04/01/2016 00:00:00:001

How to get the time of the day in milliseconds?

I want to get the time of a day in milliseconds, I do not this day to have any specific date, just a time. I made something, thought it worked, but then went debugging and concluded that it doesn't work how I want it to.
I want to use this to check if the current time is between both my specified startTime and endTime.
long startTime = settings.getLong("startTime", 0);
long endTime = settings.getLong("endTime", 0);
if ((currentTime.getMillis() >= startTime)
&& (currentTime.getMillis() <= endTime)) {
//Do stuff here
}
How I am setting the time of the propeties startTime and endTime:
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 16);
startTime.set(Calendar.MINUTE, 00);
editor.putLong("startTime",
startTime.getTimeInMillis());
Calendar endTime = Calendar.getInstance();
endTime.set(Calendar.HOUR_OF_DAY, 16);
endTime.set(Calendar.MINUTE, 00);
endTime.add(Calendar.HOUR_OF_DAY, 11);
editor.putLong("endTime",
endTime.getTimeInMillis());
editor.commit();
However this will mean that both startTimeand endTime will have this a specific date attached to it.
I hope I explained it well, any help is appreciated!
Avoid Milliseconds
No need to mess with milliseconds for your purpose. Using milliseconds for date-time is confusing and error-prone.
What you need is a decent date-time library rather than the notoriously troublesome bundled java.util.Date & .Calendar classes.
Joda-Time
If you are certain you want to ignore dates and ignore time zones, here's some example code using the LocalTime class offered by the third-party free-of-cost Joda-Time library.
LocalTime start = new LocalTime( 10, 0, 0 );
LocalTime stop = new LocalTime( 14, 30, 0 );
LocalTime target = LocalTime.now();
boolean isNowInSpan = !( ( target.isBefore( target ) ) | ( target.isAfter( stop ) ) );
Adjust that last line according to your business logic needs. You might want:
The beginning and ending are inclusive
The beginning and ending are exclusive
"Half-Open" where the beginning is inclusive and the ending is exclusive(usually best for date-time work)
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "target: " + target );
System.out.println( "isNowInSpan: " + isNowInSpan );
When run…
start: 10:00:00.000
stop: 14:30:00.000
target: 23:49:37.779
isNowInSpan: false
Another Example
Time-of-day-only is not usually the right way to go. When new to date-time work, a naïve programmer may at first think that time-only simplifies things. On the contrary, this example shows how spinning around the clock creates complications. Using date+time+timeZone is usually the best approach in the long run.
LocalTime now = LocalTime.now();
LocalTime start = new LocalTime( 13, 0, 0, 0 );
LocalTime stop = start.plusHours( 11 );
System.out.println( "now: " + now );
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
if ( now.isAfter( start ) ) {
System.out.println( "After start" );
}
if ( now.isBefore( stop ) ) {
System.out.println( "Before stop" );
}
When run…
now: 14:00:32.496
start: 13:00:00.000
stop: 00:00:00.000
After start
java.time
Java 8 brings the new java.time package, inspired by Joda-Time, defined by JSR 310.
In java.time, you will find a LocalTime class similar to the one in Joda-Time.
A new approach with Java 8 onward.
int millisecondsOfDay = LocalTime.now().get(ChronoField.MILLI_OF_DAY);
Reference: https://o7planning.org/13669/java-localtime#a64448233
Take a look at the Java 8 Time API.
http://download.java.net/jdk8/docs/api/java/time/LocalTime.html#toNanoOfDay--
Time without Date is meaning less. In Java timestamp it's using the Unix UTC and the timestamp start 0 on 01/01/1970. So, you startTime/endTime.getTimeInMillis() tell you the time different from UTC. Which mean your midnight is your base and your endTime.getTimeInMillis() will be the offset.
Calendar cal = Calendar.getInstance();
// set to mid-night
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long midnight = cal.getTimeInMillis();
cal.set(Calendar.HOUR_OF_DAY, 16);
cal.set(Calendar.MINUTE, 00);
long startTime = cal.getTimeInMillis();
editor.putLong("startTime", (startTime - midnight));
cal.add(Calendar.HOUR_OF_DAY, 11);
long endTime = cal.getTimeInMillis();
editor.putLong("endTime", (endTime - midnight));
editor.commit();
java.time.LocalTime
I recommend that you use java.time, the modern Java date and time API, for your time work. Use a LocalTime object for time of day (it’s what it’s for).
LocalTime time = LocalTime.of(16, 0);
System.out.println(time);
Output:
16:00
If you cannot store a LocalTime object in your settings, convert to a string for human readability (a great advantage in debugging and support cases):
String timeString = time.toString();
LocalTime parsedBack = LocalTime.parse(timeString);
System.out.println(parsedBack);
16:00
To answer the question as asked, in case you need to, converting to milliseconds is straightforward (when you know how):
int milliOfDay = time.get(ChronoField.MILLI_OF_DAY);
System.out.println(milliOfDay);
57600000
The milliseconds too can be converted back to a LocalTime object:
LocalTime recreatedLocalTime
= LocalTime.MIN.with(ChronoField.MILLI_OF_DAY, milliOfDay);
System.out.println(recreatedLocalTime);
16:00
Link
Oracle tutorial: Date Time explaining how to use java.time.
In case what you need is to get how many milliseconds since the start of this day and you have now in milliseconds you can get the milliseconds you want as simple as this
val nowMilliSeconds = System.currentTimeMillis() % 86400000
Where 86400000 is the number of milliseconds in a day so you will just get the remainder

Time manipulation

Given the assignment t = System.currentTimeMillis(), accrued at some point in the past, how do I get the millis of the same day as t in 12 pm and the day after 12 pm?
Note: this is timezone dependent. You can do as such:
import static java.util.Calendar.*;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourValue);
cal.set(HOUR_OF_DAY, 12);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
// cal.getTimeInMillis() contains the wanted day at 12pm
cal.add(DAY_OF_YEAR, 1);
// cal.getTimeInMillis() now contains the wanted day plus one at 12pm
But do yourself a favour and use Joda Time, it is much easier to use in this case:
final DateTime dayAt12pm = new DateTime(yourValue).toDateMidnight()
.plusHours(12);
// dayAt12pm.getMillis() contains the wanted day at 12pm
// next day at 12pm: dayAt12pm.plusDays(1).getMillis()
//plug your "T" here.
long t = System.currentTimeMillis();
Date date = new Date(t);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
startOfDay.set(Calendar.HOUR, 12);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);
Date startOfDayDate = startOfDay.getTime();
System.err.println("12PM on time t is " + startOfDayDate);
startOfDay.add(Calendar.HOUR, 24);
startOfDayDate = startOfDay.getTime();
System.err.println("12PM day after t is " + startOfDayDate);
One way would be to create a Date from it and then use the Calendar class.

Calendar add behaviour

Want to get first day of the next week (next monday), but call to getTime() changes the Calendar object.
Please tell me the right way to get first day of the next week.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final Calendar cal = new GregorianCalendar( 2013, 5, 6 );
cal.setFirstDayOfWeek( Calendar.MONDAY );
//System.out.println( sdf.format( cal.getTime() ) );
cal.set( Calendar.DAY_OF_WEEK, Calendar.MONDAY );
System.out.println( sdf.format( cal.getTime() ) ); // 2013-06-06
cal.add( Calendar.WEEK_OF_YEAR, 1 );
System.out.println( sdf.format( cal.getTime() ) ); // 2013-06-13
}
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final Calendar cal = new GregorianCalendar( 2013, 5, 6 );
cal.setFirstDayOfWeek( Calendar.MONDAY );
System.out.println( sdf.format( cal.getTime() ) ); // 2013-06-06
cal.set( Calendar.DAY_OF_WEEK, Calendar.MONDAY );
System.out.println( sdf.format( cal.getTime() ) ); // 2013-06-03
cal.add( Calendar.WEEK_OF_YEAR, 1 );
System.out.println( sdf.format( cal.getTime() ) ); // 2013-06-10
}
}
}
This is a nice example...
The Calendar is not easy to handle. You problem is the evaluation of the date.
The date of the Calendar is newly evaluated if you call e.g. getTime() or add().
In the second (correct) example you call getTime() after setting the first day of the week and the calendar is set to 2013-06-06. After that you change the day of the week and set the calendar new (via getTime()). Therefore it is now set to Monday.
In the first example you set the Calendar to the date and set the day of week. This leads to an invalid date (temporarily). 2013-06-06 is a Thursday and you set Monday. Now which one is the correct day of week? The Calendar implementation now chooses Thursday.
This is also well documented in the Javadoc. The section is named Calendar Fields Resolution.

Convert Hours to a time java

What is the best way to convert hours into the time.
Lets say 5 hours and current time is 9:17am
Now if I run the app the time should be 0417 (am)
Thanks
A sequence to do that based on current time:
Calendar cal = new GregorianCalendar();
cal.set( Calendar.HOUR_OF_DAY, 9 );
cal.set( Calendar.MINUTE, 17 );
cal.add( Calendar.HOUR_OF_DAY, -5 );
System.out.println( cal.getTime() );
You can create a new DateObject like this:
Date time5HoursBefore = new Date( System.currentTimeMillis() - 5 * 3600000 ); //3600000 is the number of milliseconds per hour
An alternative would be using Apache Commons' DateUtils:
Date time5HoursBefore = DateUtils.addHours(new Date(), -5);

Categories

Resources