This question already has answers here:
Getting specific date with timezone in Java
(1 answer)
how to get dateTime based on hour and minute
(4 answers)
Closed 1 year ago.
I am running a script in Jenkins. One piece of the script need to run at 07:00:00 Eastern Time.
The job is already scheduled on specific days and time. The job starts at 6am, but need to wait until 7am to run the next step
Using java, I can get current time/date using:
Date currentDate = new Date()
I think I need to compare currentDate with today's date at 7am so I can know how many seconds there is until 7am and put my build to sleep for that time.
My question is, how can I generate today's date at 7am?
Avoid using the terrible Date class. The legacy date-time classes were years ago supplanted by the modern java.time classes defined in JSR 310.
Capture the current moment as seen in your particular time zone.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Define your target.
LocalTime targetTime = LocalTime.of( 7 , 0 ) ;
Adjust to that time.
ZonedDateTime zdtTarget = zdt.with( targetTime ) ;
If that moment has passed, move to next day.
if( ! zdt.isBefore( zdtTarget ) ) {
zdtTarget = zdt.toLocalDate().plusDays( 1 ).atStartOfDay( z ).with( targetTime ) ;
}
Determine time to elapse.
Duration d = Duration.between( zdt.toInstant() , zdtTarget.toInstant() ) ;
Interrogate the duration object for whatever you need. For example, milliseconds:
long millis = d.toMillis() ;
Thread.sleep( millis ) ;
If you must use a java.until.Date for code not yet updated to java.time, you can convert.
java.until.Date date = Date.from( zdtTarget.toInstant() ) ;
Great question. It's easier to first create a Calendar object to set up the time, date and other custom inputs, then convert that to a Date object using the <CALENDAR_OBJECT>.getTime() member function.
EX: to get a Date object of 7 am today(10/25/2021) do the following:
Calendar cal = Calendar.getInstance(); // Calendar constructor
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.HOUR_OF_DAY,7);
cal.set(Calendar.MINUTE,00);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date d = cal.getTime(); // convert to Date obj
For more info on the Calendar obj look at some documentation by Oracle (https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html)
Related
I'm trying to make a code that tells me how many days left for me to go college, but I am not able to do it with the current date. I can easily make it by setting a date, but I want the current date, so I have to use the calendar method, but can't do math using it.
My code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
System.out.println(start - calendar.getTime());
tl;dr
ChronoUnit.DAYS.between(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ,
LocalDate.parse( "10/06/2022" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
)
Details
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date/Calendar.
Also, you are attempting to use a date-time class representing a date with time-of-day as seen in UTC (offset of zero) to hold a date-only value. Square peg, round hole.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate graduationDate = LocalDate.parse( "10/06/2022" , f ) ;
Determine today's date. That requires a time zone. For any given moment, the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; // Or ZoneId.systemDefault()
LocalDate today = LocalDate.now( z ) ;
Calculate elapsed time using java.time.temporal.ChronoUnit.
long days = ChronoUnit.DAYS.between( today , graduationDate ) ;
See this code run live at IdeOne.com.
graduationDate: 2022-06-10
today: 2022-03-05
days: 97
Tip: Learn about the ISO 8601 standard for exchanging date-time values as text.
Calendar calendar = Calendar.getInstance();
Calendar collegeDate = Calendar.getInstance();
collegeDate.set(Calendar.DATE,10);
collegeDate.set(Calendar.MONTH, 5);
collegeDate.set(Calendar.YEAR, 2022);
System.out.println(Duration.between(calendar.toInstant(), collegeDate.toInstant()).toDays());
You can try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
long dif = Math.abs(calendar.getTimeInMillis() - start.getTime());
long result = TimeUnit.DAYS.convert(dif, TimeUnit.MILLISECONDS);
System.out.println(result);
I'm trying to create a simple Alarm Clock, but I stumbled upon a problem that I can't seem to fix. I'm trying to parse a string to a date so I can get the difference between the current time and the time to set off the alarm.
Here's my code to parse the time:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
sdf.setTimeZone(getTimezone());
Date date = sdf.parse(args[0]);
Here's my getTimezone() method:
public static TimeZone getTimezone() {
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
return TimeZone.getTimeZone(name);
}
And here's my code for figuring out the difference:
long diff = date.getTime() - System.currentTimeMillis();
So my problem is that the date.getTime() returns 79680000, while System.currentTimeMillis() returns 1473538047978 (This is of course different every time, but for some odd reason, date.getTime() is not).
Which means that I get a negative number when trying to figure out the difference, and therefore I cannot use it.
EDIT: After a little bit of debugging, I realised that it has to do with the year, month and day not being set, however I do not know how to get those.
You did notice that date.getTime() returns 79680000 which is 22 hours and 20 minutes after 1 January 1970. The problem is (as you noticed) that you did not parse year, month and day.
You can do it by:
SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY hh:mm:ss");
Example input 20/04/2016 20:20:0 returns time as Mon Jan 04 20:20:00 CET 2016 (don't look at the timezone). It is 1451935200000 miliseconds after 1 January 1970.
Note: change string to match your format requirements (the syntax is self-explanatory).
The accepted answer by Ronin is correct. You are trying to put a time-of-day value into a date-time type.
java.time
Also, you are using troublesome old legacy date-time classes. Now supplanted by the java.time classes.
For a time-of-day value without a date and without a time zone, use LocalTime.
LocalTime alarmTime = LocalTime.parse( "12:34" );
Getting current time-of-day requires a time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalTime now = LocalTime.now( z );
But since we are setting an alarm, we care about the date too.
ZonedDateTime now = ZonedDateTime.now( z );
ZonedDateTime alarm = null;
if ( now.toLocalTime().isBefore( alarmTime ) ) {
alarm = ZonedDateTime.of( now.toLocalDate() , alarmTime , z );
} else {. // Else too late for today, so set alarm for tomorrow.
alarm = ZonedDateTime.of( now.toLocalDate().plusDays( 1 ) , alarmTime , z );
}
To calculate the elapsed time until the alarm, use the Duration class.
Duration untilAlarm = Duration.between( now , alarm );
You can interrogate the duration for a total number of milliseconds. But know that java.time classes are capable of handling nanoseconds.
long millis = untilAlarm.toMillis();
Updated.
You are using only time without a date with you date object in code (parses only time). If you add there date to you time, your date should be comparable to your System.getCurrentTimeMillis() call. And if you subtracting current millis from date in the past, you will have negative numbers. I prefer this convertion (date2 is after date1):
long diffInMillies = date2.getTime() - date1.getTime();
return TimeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
I must convert a linux timestamp to android date.
i get this number from server
1386889262
I have written a small code snippet.
Date d = new Date(jsonProductData.getLong(MTIME));
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy");
.setTimeZone(TimeZone.getTimeZone("GMT"));
formatTime = f.format(d);
but it doesen't convert right, this is my result
17.01.1970
EDIT:
Normally i must get this here
12.12.2013
Is there an another method to get the right date???
if your UNIX time stamp is of 10 digit then it does not include milliseconds so do this first 1386889262*1000
and if its 13 digit then it includes milliseconds also then you do not have to multiply unix timestamp with 1000.
In Kotlin we can use this function:
val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt = Date(unix);
textview.settext(dateFormat.format(dt))
UNIX timestamp should be in milliseconds so multiply the Long value by 1000. So your value 1386889262 would be 1386889262000:
tl;dr
Instant.ofEpochSecond( 1386889262L )
.atZone( ZoneId.of( "Pacific/Auckland" ) )
.toLocalDate()
.toString()
java.time
You appear to have a count of whole seconds from the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java. For older Android see the ThreeTen-Backport and ThreeTenABP projects.
An Instant represents a point on the timeline in UTC with a resolution of nanoseconds (up to nine digits of decimal fraction).
Instant instant = Instant.ofEpochSecond( 1386889262L ) ;
To generate a String representing this moment, call toString.
String output = instant.toString() ;
Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. Assign a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract a date-only value for your purposes.
LocalDate ld = zdt.toLocalDate() ;
Generate a String.
String output = ld.toString() ;
For other formats in your String, search Stack Overflow for DateTimeFormatter.
Your timestamp or epoch time seems in sec "1386889262". You have to do something like this:
long date1 = 1386889262*1000;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also get timestamp in java via
new Date().getTime() ;
It returns a long value.
I am trying to compare two calendars in java to decide if one of them is >= 24 hours ago. I am unsure on the best approach to accomplish this.
// get today's date
Date today = new Date();
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(today);
// get last update date
Date lastUpdate = profile.getDateLastUpdated().get(owner);
Calendar lastUpdatedCalendar = Calendar.getInstance();
lastUpdatedCalendar(lastUpdate);
// compare that last hotted was < 24 hrs ago from today?
tl;dr
Instant now = Instant.now();
Boolean isWithinPrior24Hours =
( ! yourJUDate.toInstant().isBefore( now.minus( 24 , ChronoUnit.HOURS) ) )
&&
( yourJUDate.toInstant().isBefore( now )
) ;
Details
The old date-time classes (java.util.Date/.Calendar, java.text.SimpleDateFormat, etc.) have proven to be be confusing and flawed. Avoid them.
For Java 8 and later, use java.time framework built into Java. For earlier Java, add the Joda-Time framework to your project.
You can easily convert between a java.util.Date and either framework.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The Instant class represents a moment on the timeline in UTC. If you meant to ask for literally 24 hours rather than "a day", then Instant is all we need.
Instant then = yourJUDate.toInstant();
Instant now = Instant.now();
Instant twentyFourHoursEarlier = now.minus( 24 , ChronoUnit.HOURS );
// Is that moment (a) not before 24 hours ago, AND (b) before now (not in the future)?
Boolean within24Hours = ( ! then.isBefore( twentyFourHoursEarlier ) ) && then.isBefore( now ) ;
If you meant "a day" rather than 24 hours, then we need to consider time zone. A day is determined locally, within a time zone. Daylight Saving Time (DST) and other anomalies mean a day is not always 24 hours long.
Instant then = yourJUDate.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime oneDayAgo = now.minusDays( 1 );
Boolean within24Hours = ( ! then.isBefore( oneDayAgo ) ) && then.isBefore( now ) ;
Another approach would use the Interval class found in the ThreeTen-Extra project. That class represents a pair of Instant objects. The class offers methods such as contains to perform comparisons.
Joda-Time
The Joda-Time library works in a similar fashion to java.time, having been its inspiration.
DateTime dateTime = new DateTime( yourDate ); // Convert java.util.Date to Joda-Time DateTime.
DateTime yesterday = DateTime.now().minusDays(1);
boolean isBeforeYesterday = dateTime.isBefore( yesterday );
Or, in one line:
boolean isBeforeYesterday = new DateTime( yourDate).isBefore( DateTime.now().minusDays(1) );
you could use Date.getTime(), here's an example:
public final static long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
public static void main(String args[]) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
boolean moreThanDay = Math.abs(date1.getTime() - date2.getTime()) > MILLIS_PER_DAY;
System.out.println(moreThanDay);
}
You can check localDateTime whether its in 24 hours or not, depending on zone offset parameter like following the example.
#Test
public void checkIsWithin24Hours() {
final ZoneOffset zoneOffset = ZoneOffset.UTC;
final LocalDateTime now = LocalDateTime.now(zoneOffset);
final LocalDateTime after = LocalDateTime.now(zoneOffset).plusHours(5);
final long nowHours = TimeUnit.MILLISECONDS.toHours(now.toInstant(zoneOffset).toEpochMilli());
final long afterFiveHours = TimeUnit.MILLISECONDS.toHours(after.toInstant(zoneOffset).toEpochMilli());
assertThat(afterFiveHours - nowHours <= 24).isTrue();
}
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Now if I want to add 2 more hours to time1, like:
7:30 + 2 = 9:30
how do I add the 2 hours?
java.util.Date is deprecated, you should use java.util.Calendar instead.
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date myDate = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.HOUR_OF_DAY,2); // this will add two hours
myDate = cal.getTime();
And even better solution is to use Joda Time - Java date and time API.
From their website - Joda-Time provides a quality replacement for the Java date and time classes.
Convert java.util.Date into java.util.Calendar Object and use Calendar.add() method to add Hours
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(time1);
cal.add(Calendar.Hour_Of_Day, 2);
time1 =cal.getTime();
System.out.println(parser.format(time1));//returns 09:30
tl;dr
LocalTime.parse( "07:30" ).plusHours( 2 )
…or…
ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) )
.plusHours( 2 )
java.time
The old date-time classes such as java.util.Date, .Calendar, and java.text.SimpleDateFormat should be avoided, now supplanted by the java.time classes.
LocalTime
For a time-of-day only value, use the LocalTime class.
LocalTime lt = LocalTime.parse( "07:30" );
LocalTime ltLater = lt.plusHours( 2 );
String output = ltLater.toString(); // 09:30
Instant
For a given java.util.Date, convert to java.time using new methods added to the old classes. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
Or capture current moment in UTC as an Instant.
Instant instant = Instant.now();
Add two hours as seconds. The TimeUnit class can convert hours to seconds.
long seconds = TimeUnit.HOURS.toSeconds( 2 );
Instant instantLater = instant.plusSeconds( seconds );
ZonedDateTime
To view in the wall-clock time of some community, apply a time zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You can add hours. The ZonedDateTime class handles anomalies such as Daylight Saving Time.
ZonedDateTime zdtLater = zdt.plusHours( 2 );
Duration
You can represent that two hours as an object.
Duration d = Duration.ofHours( 2 ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;