Today I'm parsing epoch time to a String, like this:
private String convertEpochTime(Long timeInEpoch) {
return new SimpleDateFormat("MM/dd/yyyy HH:mm")
.format(new java.util.Date (timeInEpoch * 1000));
}
I want to use Java 8 new LocalDate API, instead of using a String, but didn't find a way of doing it.
I wish I just could do:
private LocalDate convertEpochTime(Long timeInEpoch) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm").format(new java.util.Date (timeInEpoch * 1000));
return LocalDate.parse(dateTimeFormatter);
}
Is there any way of doing it?
You can use Instant.ofEpochSecond and then convert the instant to a LocalDate:
Instant instant = Instant.ofEpochSecond(timeInEpoch);
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
or if you want to have time as well, convert to a LocalDateTime:
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
Instead of ZoneId.systemDefault() you may need to use a different zone depending on your needs.
So there is no need to use a string as intermediary.
Related
I just do not quite understand which one of those two I should use for the following example:
We have an OfferEntity which has a member availableDay which is the date at which the offer is available.
Now, the table will look something like this:
CREATE TABLE IF NOT EXISTS offer (
created timestamp with time zone NOT NULL DEFAULT NOW(),
id BIGSERIAL PRIMARY KEY,
available timestamp with time zone
);
From the PostgreSQL docs we know that:
For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone.
Which means I should be fine when it comes to persisting any date/time information.
But what does this mean for my OfferEntity and the REST endpoints I define in OfferController?
#Entity
#Table(name = "offer")
public class OfferEntity {
#Column(name = "available", nullable = false)
private ZonedDateTime availableDay;
}
vs
#Entity
#Table(name = "offer")
public class OfferEntity {
#Column(name = "available", nullable = false)
private Instant availableDay;
}
From what I understood - this should not make a difference. PostgreSQL stores everything as UTC anyway so I should be able to take Instant or ZonedDateTime right? Write something -> UTC. Read it again -> still UTC.
Even the client won't be able to tell the difference:
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public Object hello() {
class Hello {
public Instant instant = Instant.now();
public ZonedDateTime zonedDateTime = ZonedDateTime.now();
public ZonedDateTime viennaTime = ZonedDateTime.now(ZoneId.of("GMT+2"));
public LocalDateTime localDateTime = LocalDateTime.now();
}
return new Hello();
}
Will return:
{
"instant": "2018-10-07T15:30:08.579Z",
"zonedDateTime": "2018-10-07T15:30:08.579Z",
"viennaTime": "2018-10-07T17:30:08.579+02:00",
"localDateTime": "2018-10-07T15:30:08.579",
}
But there must be a crucial difference which I am apparently not seeing.
There are two differences I can make out. It seems to be that Spring has no problem with converting "2018-10-07T15:30:08.579Z" to an Instant object, but fails to do so if I change the type to ZonedDateTime. At least out of the box.
#RequestMapping("/places/{placeId}/offers", method = RequestMethod.GET)
public List<OfferDto> getOffers(
#PathVariable(name = "placeId") Long placeId,
#RequestParam(name = "date") ZonedDateTime date) {
return this.offerService.getOffers(placeId, date);
}
The other difference is the fact that if I use Instant I am forcing my clients to convert all their date/time strings to UTC first. So any client will have to myDate.toUTCString() first. ZonedDateTime would take anything as long as it has a time zone set but why would we care?
So which of the two is the better choice and why would I chose one over the other?
The answer in the following link explains it better than I ever could. The answer goes into all the different date/time classes in Java, as well as their relation to sql types.
What's the difference between Instant and LocalDateTime?
A short summary:
The classes Instant and ZonedDateTime (as well as OffsetDateTime)
represent the same thing: a moment in time. The difference is that
ZonedDateTime and OffsetDateTime offer extra context and functionality
about timezones or time offsets, whereas Instant has no timezone or
offset specified. This can lead to differences especially when Daylight Saving Time is involved. For instance, take the following snippet of code:
ZonedDateTime z1 = zonedDateTime.of(LocalDateTime.of(2019,10,26,6,0,0),ZoneId.of("Europe/Amsterdam"));
Instant i1 = z1.plus(1,ChronoUnit.DAYS).toInstant();
Instant i2 = z1.toInstant().plus(1,ChronoUnit.DAYS);
System.out.println(i1);
System.out.println(i2);
The result will be this:
2019-10-27T05:00:00Z
2019-10-27T04:00:00Z
The difference stems from the fact that in the Amsterdam timezone, the 27th of October has an extra hour. When we convert to Instant the timezone information is lost, so adding a day will add only 24 hours.
LocalDateTime is a different beast alltogether. It represents a date
and time without timezone information. It does not represent a
moment in Time. It is useful for writing things such as "Christmas
morning starts at december 25th 00:00:00". This is true regardless of
timezone, and as such a ZonedDateTime or Instant would not be appropriate.
I've got the following date as a string
2017-03-01T10:15:41-0800
that I'm trying to use with
new Date().parse('dd/mm/yyyy', dateString)
However, I can't figure out the format.
Your dateString and date format dont match.
Groovy Style:
def dateString = "2017-03-01T10:15:41-0800"
new Date().parse("yyyy-MM-dd'T'HH:mm:ssZ", dateString)
Result:
Wed Mar 01 21:15:41 EAT 2017
You can refer here for more information about the date format pattern.
Consider using SimpleDateFormat:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date parsed = format.parse("2017-03-01T10:15:41-0800");
} catch (ParseException e){
e.printStackTrace();
}
}
}
Try it here!
Date class contains its own, static parse method (JB Nizet was wrong in his comment to your question).
For details see http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Date.html#parse(java.lang.String,%20java.lang.String)
So if you perform this parsing only once, use just this method.
On the other hand, if you plan to perform such a conversion multiple times,
it is more efficient to create a SimpleDateFormat instance (once)
and then use it multiple times.
If you can, and you're on Java 8, avoid java.util.Date, and parse it into one of the new java.time classes:
import java.time.*
import java.time.format.DateTimeFormatter
def dateString = "2017-03-01T10:15:41-0800"
def date = OffsetDateTime.parse(dateString,
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
If you then want this time in another zone (ie: UTC), you can do:
def utcDate = date.atZoneSameInstant(ZoneOffset.UTC)
I have a certain records in ignite cache and I want to retrieve all records for current day. For this I need to compare LocalDateTime type field of cached object with Localdate object i.e LocalDate.now(). How do I write a query to do this. In oracle TODATE(date, format) does the same thing but this function is not present in H2.
cached field datetime: 2016-08-30T05:31
date instance : 2016-08-30
SQL will be like
String sql = "select * from cacheName where date='convert(datetime) to date'";
Is it possible in H2 ?
You can use custom SQL functions for this: https://ignite.apache.org/releases/mobile/org/apache/ignite/cache/query/annotations/QuerySqlFunction.html
For example, if your value class looks like this:
public class MyValue {
#QuerySqlField
private LocalDateTime time;
public MyValue(LocalDateTime time) {
this.time = time;
}
}
You can create a function like this:
public static class MyFunctions {
#QuerySqlFunction
public static String toDate(LocalDateTime time) {
return time.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
And provide it in the configuration like this:
cacheCfg.setSqlFunctionClasses(MyFunctions.class);
The query will look like this:
select * from MyValue where toDate(time) = '2016-08-30'
How can I best convert a java.util.Date to a Java 8 java.time.YearMonth?
Unfortunately the following throws a DateTimeException:
YearMonth yearMonth = YearMonth.from(date.toInstant());
results in:
java.time.DateTimeException: Unable to obtain YearMonth from TemporalAccessor: 2015-01-08T14:28:39.183Z of type java.time.Instant
at java.time.YearMonth.from(YearMonth.java:264)
...
I need this functionality since I want to store YearMonth values in a database using JPA. Currently JPA does not support YearMonth's, so I've come up with the following YearMonthConverter (imports omitted):
// TODO (future): delete when next version of JPA (i.e. Java 9?) supports YearMonth. See https://java.net/jira/browse/JPA_SPEC-63
#Converter(autoApply = true)
public class YearMonthConverter implements AttributeConverter<YearMonth, Date> {
#Override
public Date convertToDatabaseColumn(YearMonth attribute) {
// uses default zone since in the end only dates are needed
return attribute == null ? null : Date.from(attribute.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
}
#Override
public YearMonth convertToEntityAttribute(Date dbData) {
// TODO: check if Date -> YearMonth can't be done in a better way
if (dbData == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(dbData);
return YearMonth.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
}
}
Isn't there a better (cleaner, shorter) solution (for both directions)?
Short answer:
// From Date to YearMonth
YearMonth yearMonth =
YearMonth.from(date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());
// From YearMonth to Date
// The same as the OP:s answer
final Date convertedFromYearMonth =
Date.from(yearMonth.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
Explanation:
The JavaDoc of the YearMonth.from(TemporalAccessor)-method says:
The conversion extracts the YEAR and MONTH_OF_YEAR fields. The extraction is only permitted if the temporal object has an ISO chronology, or can be converted to a LocalDate.
So, you need to either be able to:
extract the YEAR and MONTH_OF_YEAR fields, or
you should use something that can be converted to a LocalDate.
Lets try it!
final Date date = new Date();
final Instant instant = date.toInstant();
instant.get(ChronoField.YEAR); // causes an error
This is not possible, an exception is thrown:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
at java.time.Instant.get(Instant.java:571)
...
This means that alternative 1 goes out the window. The reason for is explained in this excellent answer about how to convert Date to LocalDate.
Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion.
So, a Date can be converted to an Instant but that did not help us, did it?
Alternative 2 however proves to be successful. Convert the Instant to a LocalDate and then use the YearMonth.from(TemporalAccessor)-method.
Date date = new Date();
LocalDate localDate = date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
YearMonth yearMonth = YearMonth.from(localDate);
System.out.println("YearMonth: " + yearMonth);
The output is (since the code was executed in January 2015 ;):
YearMonth: 2015-01
I have date in this format 2011-11-02. From this date, how can we know the Day-of-week, Month and Day-of-month, like in this format Wednesday-Nov-02, from calendar or any other way?
If it were normal java, you would use two SimpleDateFormats - one to read and one to write:
SimpleDateFormat read = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat write = new SimpleDateFormat("EEEE-MMM-dd");
String str = write.format(read.parse("2011-11-02"));
System.out.println(str);
Output:
Wednesday-Nov-02
As a function (ie static method) it would look like:
public static String reformat(String source) throws ParseException {
SimpleDateFormat read = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat write = new SimpleDateFormat("EEEE-MMM-dd");
return write.format(read.parse(source));
}
Warning:
Do not be tempted to make read or write into static fields to save instantiating them every method invocation, because SimpleDateFormat is not thread safe!
Edited
However, after consulting the Blackberry Java 5.0 API doc, it seems the write.format part should work with blackberry's SimpleDateFormat, but you'll need to parse the date using something else... HttpDateParser looks promising. I don't have that JDK installed, but try this:
public static String reformat(String source) {
SimpleDateFormat write = new SimpleDateFormat("EEEE-MMM-dd");
Date date = new Date(HttpDateParser.parse(source));
return write.format(date);
}