This question already has answers here:
How to get and set specified time in java.time.Instant?
(4 answers)
Closed 3 years ago.
Consider the below code
Instant instant = Instant.now();
System.out.println(instant);
RESULT:
2020-01-13T09:01:06.405Z
Now from the above result I want get the current hour and current minutes.
instant.atZone(ZoneOffset.UTC).getMinute()
and
instant.atZone(ZoneOffset.UTC).getHour()
(That's for UTC; otherwise choose your time zone).
If you want to know the single parts of an Instant for the time zone of your system, then do this:
public static void main(String[] args) {
Instant instant = Instant.now();
// convert the instant to a local date time of your system time zone
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
int day = ldt.getDayOfMonth();
int month = ldt.getMonthValue();
int year = ldt.getYear();
int hour = ldt.getHour();
int minute = ldt.getMinute();
int second = ldt.getSecond();
System.out.println("day:\t" + day);
System.out.println("month:\t" + month);
System.out.println("year:\t" + year);
System.out.println("hour:\t" + hour);
System.out.println("minute:\t" + minute);
System.out.println("second:\t" + second);
}
On my system, the output was:
day: 13
month: 1
year: 2020
hour: 10
minute: 38
second: 51
Otherwise (if you want to have UTC time zone) use one of the other answers, which are basically the same code but putting a different time zone.
Can you try to do this
System.out.println("Get Hours "+LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour());
System.out.println("Get Minute "+LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getMinute());
Related
This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Calculating the difference between two Java date instances
(45 answers)
The difference between 2 Instants in Calendar Days
(4 answers)
Closed 1 year ago.
I have a scenario where epoch time is in string . I need to convert this to number of days ago from current time .
Eg:
String epoch = "1600852773514";
Date expiry = new Date(Long.parseLong(epoch));
Expiry gives me Wed Sep 23 14:49:33 IST 2020 .But I want to get number of days from today to the time 'epoch' . Like epoch is 240 days ago from today.
If expiry > 30 days
pass
else
fail
You can do something like this:
Date expiry = /* ... */;
Date now = new Date();
long days = (now.getTime() - expiry.getTime()) / 86_400_000;
if (days > 30) /* ... */
So we take the difference of the time in milliseconds:
long diff = (now.getTime() - expiry.getTime());
If we divide by 86.000.000 (this is how many milliseconds a day has), we get the number of past days.
As an alternative, you could use java.time (since Java 8) and count the days between two dates:
public static void main(String[] args) {
// example String
String epoch = "1618991673000";
// parse it to a long
long epochMillis = Long.parseLong(epoch);
// then create an Instant from that long value
Instant instant = Instant.ofEpochMilli(epochMillis);
// and convert it to an OffsetDateTime at UTC (+00:00)
OffsetDateTime odt = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
// get today's date (only, no time of day considered)
LocalDate today = LocalDate.now();
// and extract the date of the OffsetDateTime
LocalDate then = odt.toLocalDate();
// count the days between the two dates
long daysGone = ChronoUnit.DAYS.between(then, today);
// and print the result...
System.out.println("Days between " + then
+ " and today (" + today + "): " + daysGone);
}
This outputs (today, 21st of May 2021):
Days between 2021-04-21 and today (2021-05-21): 30
Afterwards, you can easily check if the amount of days is greater or less than allowed in your scenario.
Converting to Instance's and using Duration class:
String epoch = "1600852773514";
Instant start = Instant.ofEpochMilli(Long.parseLong(epoch));
Instant now = Instant.now();
Long diff = Duration.between(start,now).toDays();
System.out.println(diff);
I want to convert the given HH:mm from UTC to different time zones.
String myDateString = "02:30";
LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int second = localTime.get(ChronoField.SECOND_OF_MINUTE);
System.out.println("UTC Time is "+ hour + ":" + minute);
Calendar pstTime = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
hour = pstTime.get(hour);
minute = pstTime.get(minute);
getting error with this. any help appreciated.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
30
As already said, a time zone without day part misses information considering DST.
So it is:
String myDateString = "02:30";
LocalTime localTime = LocalTime.parse(myDateString,
DateTimeFormatter.ofPattern("HH:mm"));
LocalDateTime localDateTime = localTime.atDate(LocalDate.now());
System.out.println("localDateTime: " + localDateTime);
ZonedDateTime zonedDateTimeUTC = localDateTime.atZone(ZoneId.of("UTC"));
System.out.println("zonedDateTimeUTC: " + zonedDateTimeUTC);
ZonedDateTime zonedDateTimePST = zonedDateTimeUTC.withZoneSameInstant(
ZoneId.of("America/Los_Angeles"));
System.out.println("zonedDateTimePST: " + zonedDateTimePST);
int hour = zonedDateTimePST.getHour();
int minute = zonedDateTimePST.getMinute();
int second = zonedDateTimePST.getSecond();
There is no need for the old Calendar class.
I think you should specify date too. For that problem you can use this block of code
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
.ofPattern("MM/dd/yyyy'T'HH:mm z");
String inputValue = "08/03/2020T15:20 UTC";
ZonedDateTime zdtInstanceAtOffset = ZonedDateTime.parse(inputValue, DATE_TIME_FORMATTER);
ZonedDateTime zonedDateTime = zdtInstanceAtOffset.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
System.out.println(zonedDateTime);
Without a date, you can convert a time, given for one timezone, to another timezone only by adding/subtracting the time difference between the source timezone and the target timezone to/from the given time.
The problem with this approach is, that the time difference between timezones is not constant over the year, when it is identified by "region/location" (like "America/Los Angeles"). If you use "EST" or "GMT" or "CET" (sometimes referred to as "zone times") instead, the differences would be stable – but you are still inaccurate: several timezones will have two zone times, depending on the time in the year …
You can use the java.time.ZonedDateTime class for this and the method withZoneSameInstant(ZoneId zone) which returns a copy of the datetime in the specified zone.
Here is an example if your input time is in UTC timezone. To change the zone of the input time change Zone inputZone to ZoneId.of("<your timezone>");
public static void main(String[] args) {
String timeString = "02:30";
// Change this to the zone of the input time
ZoneId inputZone = ZoneId.of("UTC");
// Parse your input into time
LocalTime time = LocalTime.parse(timeString);
// Add current date to the time, you can add custom date using LocalDate.of(int year, int month, int dayOfMonth)
LocalDateTime localDateTime = time.atDate(LocalDate.now());
// Declare zoned date time with input zone specified
ZonedDateTime zonedDateTime = localDateTime.atZone(inputZone);
// Declare zones you will use
ZoneId myZone = ZoneId.systemDefault();
ZoneId utcZone = ZoneId.of("UTC");
ZoneId nyZone = ZoneId.of("America/New_York");
ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");
// Get times in different timezones
ZonedDateTime myDateTime = zonedDateTime.withZoneSameInstant(myZone);
ZonedDateTime utcDateTime = zonedDateTime.withZoneSameInstant(utcZone);
ZonedDateTime nyDateTime = zonedDateTime.withZoneSameInstant(nyZone);
ZonedDateTime tokyoDateTime = zonedDateTime.withZoneSameInstant(tokyoZone);
// Print the times in different timezones
System.out.println("My Timezone: " + myDateTime);
System.out.println("UTC: " + utcDateTime);
System.out.println("NY: " + nyDateTime);
System.out.println("Tokyo: " + tokyoDateTime);
// Print without the offset
System.out.println("My Timezone: " + myDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println("UTC: " + utcDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println("NY: " + nyDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println("Tokyo: " + tokyoDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
This code will generate the following output:
My Timezone: 2020-03-11T03:30+01:00[Europe/Zagreb]
UTC: 2020-03-11T02:30Z[UTC]
NY: 2020-03-10T22:30-04:00[America/New_York]
Tokyo: 2020-03-11T11:30+09:00[Asia/Tokyo]
My Timezone: 2020-03-11T03:30:00
UTC: 2020-03-11T02:30:00
NY: 2020-03-10T22:30:00
Tokyo: 2020-03-11T11:30:00
This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Converting Long to Date in Java returns 1970
(12 answers)
android timestamp parsing gone wrong(always in 1970)
(4 answers)
Closed 3 years ago.
I want to convert 1574348400 value to date format using code:
public class Main {
public Main() {
long value = 1574348400;
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(new Date(value));
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new Main();
}
}
I want to get the output as: Wednesday 20 November, 2019 but I'm getting Monday 19 January, 1970. How to get the current date not the 1970's date?
Parse your time (in seconds) using java.time, it provides a method for epoch seconds...
public static void main(String[] args) {
// your seconds
long seconds = 1574348400;
// same in millis
long millis = 1574348400000L;
// find out the zone of your system
ZoneId systemDefaultZoneId = ZoneId.systemDefault();
// or set a specific one
ZoneId utcZoneId = ZoneId.of("UTC");
// parse a ZonedDateTime of your system default time zone from the seconds
ZonedDateTime fromSecsSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the seconds
ZonedDateTime fromSecsUtc = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
utcZoneId);
// parse a ZonedDateTime of your system default time zone from the milliseconds
ZonedDateTime fromMillisSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the milliseconds
ZonedDateTime fromMillisUtc = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
utcZoneId);
// print the ones that were created using your default time zone
System.out.println("from seconds:\t"
+ fromSecsSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsSysDefZone.equals(fromMillisSysDefZone) ? "equal" : "different"));
System.out.println("————————————————————————————————");
// print the ones that were created using UTC
System.out.println("from seconds:\t"
+ fromSecsUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsUtc.equals(fromMillisUtc) ? "equal" : "different"));
}
The output produced by this code (on my system) is
from seconds: 2019-11-21T16:00:00+01:00[Europe/Berlin]
from millis: 2019-11-21T16:00:00+01:00[Europe/Berlin]
Both ZonedDateTimes are equal
————————————————————————————————
from seconds: 2019-11-21T15:00:00Z[UTC]
from millis: 2019-11-21T15:00:00Z[UTC]
Both ZonedDateTimes are equal
If you have to use Java 6 or 7, then you can use the ThreeTenBackport-Project on Github, which enables (most) functionality of java.time in those two older versions.
Its use is explained on a separate website.
Wrong value. Try:
long value = 1574348400000L;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class BasicWebCrawler {
public BasicWebCrawler() {
long value = 1574348400000L;
Date date = new Date(value);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
Date minusOne = cal.getTime();
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(minusOne);
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new BasicWebCrawler();
}
}
output : Formated time: Wednesday 20 November, 2019
Your first issue is: You are using seconds instead of milliseconds, new Date(long) the value of long is in milliseconds.
See the Java 6 java.util.Date Documentation here
Your second issue is: When using Java 6 Date you need to know where the value in milliseconds was determined, if it's not in your timezone then you will need to make a conversion. Take the following code for example:
String zeroDateString = new SimpleDateFormat("EEEE dd MMMM, yyyy hh:mm").format(new Date(0));
System.out.println("Formated time -- zeroDateString = " + zeroDateString);
The output of new Date(0) in NYC, NY, USA will be Wednesday December 31, 1969 19:00 (the timezone of New-York City is EST which is GMT-05:00) while in Rome, Italy the output of the same code will be Thursday 01 January 1970 01:00 (the timezone of Rome, Italy is GMT+01:00)
If you need all your data to be according to GMT then you will need to make adjustment and/or calculation according to your timezone in relation to GMT.
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);
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
Im trying to calculate the time difference between 2 Timestamps, this is the code:
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
Timestamp currentTimestamp = new Timestamp(now.getTime());
System.out.println("Current\n"+currentTimestamp);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("28/02/2015");
Timestamp timestampBefore = new Timestamp(date.getTime());
System.out.println("Before\n"+timestampBefore);
Timestamp calculated = new Timestamp(currentTimestamp.getTime() - timestampBefore.getTime());
System.out.println("Calculated\n"+calculated);
Output:
Current
2015-02-28 12:12:40.975
Before
2015-02-28 00:00:00.0
Calculated
1970-01-01 13:12:40.975
I can understand why it returns 1970-01-01 but why does it return 13:12:40.975 ,1 hour more?
How to calculate the difference between 2 dates so the output is like this (based on this example):
Years:0, Months:0, Days:0, Hours:12, Minutes:12, Seconds:40 ?
Update: for java below 1.8 check out http://www.joda.org/joda-time/index.html
and for java 1.8 see answer.
Similar solution here: Java 8: Calculate difference between two LocalDateTime
(1) A timestamp is a point in time. If you calculate the difference between two timestamps, the result is not a timestamp (point in time), but a duration. So it is nonsense to convert the difference to a timestamp, hence it is useless to discuss the reason why the result is strange.
(2) You should probably use the new Java 8 time API (if you are able to use Java 8):
LocalTime now = LocalTime.now();
LocalTime previous = LocalTime.of(0, 0, 0, 0);
Duration duration = Duration.between(previous, now);
System.out.println(now);
System.out.println(previous);
System.out.println(duration);
Note that this just calculates the duration between two times of a day (hour-minute-second). If your want to include date information, use LocalDateTime instead:
LocalDateTime nextFirework = LocalDate.now()
.with(TemporalAdjusters.firstDayOfNextYear())
.atTime(LocalTime.MIDNIGHT);
LocalDateTime now = LocalDateTime.now();
// duration (in seconds and nanos)
Duration duration = Duration.between(now, nextFirework);
// duration in total hours
long hours = now.until(nextFirework, ChronoUnit.HOURS);
// equals to: duration.toHours();
If you want to have 'normalized' duration in years/months/days/hours/seconds, there is suprisingly no direct support. You could convert the duration to days, hours, minutes and seconds by yourself:
long d = duration.toDays();
long h = duration.toHours() - 24 * d;
long m = duration.toMinutes() - 60 * duration.toHours();
long s = duration.getSeconds() - 60 * duration.toMinutes();
System.out.println(d + "d " + h + "h " + m + "m " + s + "s ");
But note that you will have difficulties converting the days into months and years, as there is no unique number of days per month and a year can be a leap year with 366 days. For that, you can use Period, as in opposite to Duration, this class is associated with a timeline. Unfortunately, Period does only support dates, but no times:
// period in years/months/days (ignoring time information)
Period p = Period.between(now.toLocalDate(), nextFirework.toLocalDate());
System.out.println(p); // or use p.getYears(), p.getMonths(), p.getDays()
So probably you could combine both approaches - first, compute the Period from the dates and then the Duration using the times. Note that the duration can be negative, so you'll have to take care of that in case of:
Duration dur = Duration.between(start.toLocalTime(), end.toLocalTime());
LocalDate e = end.toLocalDate();
if (dur.isNegative()) {
dur = dur.plusDays(1);
e = e.minusDays(1);
}
Period per = Period.between(start.toLocalDate(), e);
System.out.println(per.toString() + ", " + dur.toString());