Can't find any solution how to get tomorrow's date 13:00.
For example: today is 16.01.2019, I need to find how in unix timestrap is 17.01.2019 13:00.
tried this:
LocalDateTime tomorrowWithTime =
LocalDateTime.of(LocalDate.now().plusDays(1), 13:00);
to set manually 13:00, add it to tomorrows date and then convert to unix timestrap, but no luck :(
You were very close to it. To get the LocalDateTime it's
LocalDateTime tomorrowWithTime = LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.of(13, 0));
Then to convert it to unix timestamp please have a look at this question. In summary you have to give a ZoneId: (to give a working answer I'll use your system zoneId):
ZoneId zoneId = ZoneId.systemDefault(); //Or the appropriate zone
long timestamp = tomorrowWithTime.atZone(zoneId).toEpochSecond();
By the way, if your issue was that you didn't know what to give as parameters to LocalDateTime.of(), your first reflex should be to have a look at the API to see what parameters it accepts.
Related
I have a Spring Boot JPA Application that interacts with a 3rd party API.
The response payload of the API has a key
"created_at": 1591988071
I need to parse this field into java.time.Instant so that I can do some comparisons with the value I have in the Database.
I have learned that I can use the below mentioned piece of code.
Instant instant = Instant.ofEpochSecond(1591988071);
Output :
2020-06-12T18:54:31Z
But to be honest, this output is off by a couple of hours.
I found another approach, wherein if I use
String dateAsText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(1591988071 * 1000L));
System.out.println(dateAsText);
I get the desired output but in String format.
2020-06-13 00:24:31
Can someone tell me how to obtain the above String output but converted into type java.time.Instant ?
It is likely you're in a different timezone than UTC. The instant is giving you time in UTC. That's indicated by the Z at the end of your first output.
You would want to look at atZone
Instant instant = Instant.ofEpochSecond(1591988071);
System.out.println(instant);
final ZonedDateTime losAngeles = instant.atZone(ZoneId.of("America/Los_Angeles"));
System.out.println(losAngeles);
final ZonedDateTime mumbai = instant.atZone(ZoneId.of("UTC+0530"));
System.out.println(mumbai);
This gives you something you might expect
2020-06-12T18:54:31Z
2020-06-12T11:54:31-07:00[America/Los_Angeles]
2020-06-13T00:24:31+05:30[UTC+05:30]
In the code bellow, i'm getting an error in my "if" comparisson. The message says "isBefore(java.time.chrono.ChronoZonedDateTime<?>) in ChronoZonedDateTime cannot be applied to (java.time.LocalDate)". How convert LocalDate to ChronoZonedDateTime?
LocalDate taxBegin = tax.getBeginAt();
if(contract.getBeginAt().isBefore(taxBegin)){
//do something
}
I tried wrapping like ChronoZonedDateTime.from(taxBegin) but didn't work, it gave me "DateTimeException: Unable to obtain ZoneId from TemporalAccessor: 2019-12-01 of type java.time.LocalDat"
In order to convert a ZonedDateTime object into a LocalDate, you can use toLocalDate() method. Thus, the following code should work for you:
LocalDate taxBegin = tax.getBeginAt();
if(contract.getBeginAt().toLocalDate().isBefore(taxBegin)){
//do something
}
Check https://howtodoinjava.com/java/date-time/localdate-zoneddatetime-conversion/ for an example of converting between ZonedDateTime and LocalDate.
You could use atStartOfDay(ZoneId)
I.E.
public static ZonedDateTime convertLocalDate(final LocalDate ld) {
return ld.atStartOfDay(ZoneId.systemDefault());
}
You could either use ZoneId.systemDefault() or ZoneOffset.UTC.
Documentation states: If the zone ID is a ZoneOffset, then the result always has a time of midnight.
So your code'll be
if (contract.getBeginAt().isBefore(convertLocalDate(taxBegin))) {
//do something
}
If you want to convert it to a specific time, you should use
taxBegin.atTime(LocalTime).atZone(ZoneId).
If you had LocalDateTime instead of LocalDate, it would have worked just fine. But since you have LocalDate, you lost time. Now the only way is to convert the existing ChronoZonedDateTime to LocalDate and compare. However, this may not always work if the time zones are different.
Same timezone:
contract.getBeginAt().toLocalDate().isBefore(taxBegin)
The problem is, that I have to change my code from Calendar object to LocalDateTime object. But I don't get the same timestamp at the end. In the first call I got the same with localDateTime, on the next calls I get other timestamps and I use the same parameter to calculate the timestamps. I don't know why I get different results. It isn't logic for me. What I want to do is: I get a UTC Timestamp. I want to set it on german(Europe/Berlin) time(important about summer and winter season). Then I want to calculate the start of the day(00:00) and the end of the day(23:59). Then I want to get the timestamp for this times.
I build an API with spring-boot. The above described function is invoked by a controller class from spring-boot. The first call after the start of the API calculates the expected results. But all next calls give other results. Always with 7200 difference. I tried other ways with localDateTime, but it never gaves the same timestamp as with calendar.
LocalDateTimeWay:
LocalDateTime localDateTime =
LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
LocalDateTime dayStartLocal = localDateTime.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
ZonedDateTime startZonedDateTime = dayStartLocal.atZone(ZoneId.systemDefault());
long dayStartTimeStamp = startZonedDateTime.toInstant().getEpochSecond();
LocalDateTime dayEndLocal = localDateTime.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999);
ZonedDateTime endZonedDateTime = dayEndLocal.atZone(ZoneId.systemDefault());
long dayEndTimeStamp = endZonedDateTime.toInstant().getEpochSecond();
CalendarWay:
Calendar cal=Calendar.getInstance();
cal.setTimeInMillis(timestamp*1000);
cal.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
long dayStartTimeStamp = calendar.getTimeInMillis()/1000L;
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE,59);
cal.set(Calendar.SECOND,59);
cal.set(Calendar.MILLISECOND,999);
long dayEndTimeStamp = calendar.getTimeInMillis()/1000L;
I want by the param timestamp 1536933600. The result 1536876000 and 1536962399. But I get after the first request by localDateTime method 1536883200 and 1536969599.
You are using system default zone for your java.time code and Europe/Berlin zone for Calendar code. The 7200 is most likely the difference between your system time zone and Europe/Berlin (2 hours).
Replace all ZoneId.systemDefault() with ZoneId.of("Europe/Berlin") and you will get the same values in both versions:
timestamp = 1536933600
dayStartTimeStamp = 1536876000
dayEndTimeStamp = 1536962399
I have got a String of Date which has the nonstandard GMT format, like "2016-08-31T02:04:58.893GMT".
Now I need to transfer it to Local time format, like "2016-08-31 10:04:58". By the way, I am in China, there's 8 hours between the Local time and GMT time.
Oh, I use Java. Thank everyone.
You parse the string using DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").
Example code, showing intermediate results:
String input = "2016-08-31T02:04:58.893GMT";
DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
ZonedDateTime zdtGMT = ZonedDateTime.parse(input, fmt1);
System.out.println(zdtGMT); // prints 2016-08-31T02:04:58.893Z[GMT]
ZonedDateTime zdtChina = zdtGMT.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
System.out.println(zdtChina); // prints 2016-08-31T10:04:58.893+08:00[Asia/Shanghai]
LocalDateTime ldt = zdtChina.toLocalDateTime();
System.out.println(ldt); // prints 2016-08-31T10:04:58.893
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(ldt.format(fmt2)); // prints 2016-08-31 10:04:58
You'd better transform the non-standard GMT format to a standard time format and then use some proper built-in function to add or subtract a difference. You may use another function to transform the standard time format to your designated format.
This will be great because you don't have to consider the complicated cases, for example, "2016-12-31 23:00" + 8hrs.
After a week of going through so many examples, and moving from Java Date,
to Calendar, to Joda. I have decided to seek help from other sources.
The problem:
Our table has two fields Date (Timestamp), and TZ (String). The idea is to store
the user's UTC in timestamp, and timezone, well, you get the idea. So basically
we think in UTC, and present the user with the time converted to their
timezone on the front end (ie, using the value store in table.TZ)
Another requirement is to use the proper Object (Date, DateTime whatever).
And not pass a String representation of the date around. The best would
be a valid Long that will be correctly translated by MySQL, without having
to use the FROM_UNIXTIME mysql function in our query.
Code we are using:
public DateTime convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withLocale(l);
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
System.out.println(formatter.print(dstDateTime));
System.out.println(formatter.parseDateTime(dstDateTime.toString()));
return formatter.parseDateTime(formatter.print(dstDateTime));
}
The String output is exactly what we need (ie UTC time, 2013-08-23 18:19:12),
but the formatter.parseDateTime(dstDateTime.toString() is crashing with the following
error. Probably because of the UTC timezone independent info, and milleseconds?:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2013-08- 23T18:19:12.515Z" is malformed at "T18:19:12.515Z"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
at com.example.business.rate.RateDeck.convertTimezone(RateDeck.java:75)
at com.example.business.rate.RateDeck.WriteData(RateDeck.java:143)
at com.example.business.rate.RateDeck.main(RateDeck.java:64)
Search engine enriched question:
How to format UTC for Joda DateTime.
PS My first SO post, and it feels nice? :)
Thanks in Advance,
The new fixed version:
public Timestamp convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
return new Timestamp(dstDateTime.getMillis());
}
Nick.
It's simply crashing because the format of the parsed string doesn't match with the format of the formatter.
The formatter parses using the format yyyy-MM-dd HH:mm:ss, and the toString() method of DateTime formats the date it using (as documented) the ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).