Converting java.lang.double to org.joda.time.Instant - java

I have looked around a lot. I am very new to Java, and I am trying to cast a Double into an Instant. The use case is for the Google Dataflow Java SDK. The Double is a UNIX timestamp from a file I read using TextIO. When I System.out.println(row.get("timestamp")) I indeed get UNIX timestamps. When I do System.out.println(row.get("timestamp").getClass().getName()), then I get java.lang.double. what I have is as follows:
static class ExtractTimestamp extends DoFn<TableRow, TableRow> {
#Override
public void processElement(ProcessContext c) {
TableRow row = c.element();
Instant timestamp = (Instant) row.get("timestamp");
c.outputWithTimestamp(row, timestamp);
}
}
The error I am getting is:
java.lang.Double cannot be cast to org.joda.time.Instant
The problem is that I want to cast the UNIX timestamps that are in double to Instants so I can pass it to outputWithTimestamp. I believe this should be a trivial problem, but I wasn't able to find the solution yet. Thank you.

You can't "cast" a Double to an Instant. You need to pass your timestamp as a constructor argument:
Instant timestamp = new Instant(((Number)row.getTimestamp("timestamp")).longValue());
This assumes the "timestamp" value is in milliseconds. If it's seconds, just multiply by 1000.

Related

Java GSON Escaping backslashes in a custom serializer

I need to serialize a Java LocalDate (e.g. 2020-02-04) into the following format:
"myProperty":"\/Date(-2209165200000+0100)\/", as the interface we work with requests that format.
We are currently using the newest version of GSON (2.8.6)
Our custom LocalDate Serializer looks like this at the moment:
public class LocalDateSerializer implements JsonSerializer<LocalDate> {
#Override
public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
Instant instant = src.atStartOfDay(ZoneId.systemDefault()).toInstant();
long timeInMillis = instant.toEpochMilli();
ZoneOffset offset = OffsetDateTime.now().getOffset();
return context.serialize("\\/Date(" + timeInMillis + offset + ")\\/");
}
}
The issue now is that, as far as I know, that the context.serialize function escapes the double backslashes, so the final result is "myProperty":"\\/Date(-2209165200000+0100)\\/" instead of "myProperty":"\/Date(-2209165200000+0100)\/"
And in Java 1.8 you are not allowed to simply have a String like "\/", as this will result in a compiler error.
Is there any simple way of getting our result with single backslashes?
Thanks and kind regards :)
Marco
As specified in RFC 7159, \/ represents an escaped forward slash and decodes to \.
Consequently, you want to return context.serialize("/Date(" + timeInMillis + offset + ")/");.
We fixed our problem by returning a new JsonPrimitive instead of using context
So we are using return new JsonPrimitive("/Date(" + timeInMillis + offset + ")/"); now and everything works fine now. Still thanks for the input though, much appreciated!

Java current time different values in api

I'm a little confused using the DateTime related class for Java SE 7 and 8 API's, for displaying the current time, I'm reviewing the multiple ways for get the system's current datetime.
My question is: Which one is more accurate for displaying time in millis?
Next is the code snippet, I'm using Java 8 for the reviewing.
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeValidationDemo {
public static void main(String[] args) {
Instant now = Instant.now();
Calendar calendar=Calendar.getInstance();
Date currDate = new Date();
System.out.println("new Date().getTime() = "+currDate.getTime());
System.out.println("System.currentTimeMillis() = "+System.currentTimeMillis());
System.out.println("Instant.now().toEpochMilli() = "+now.toEpochMilli());
System.out.println("Calendar.getInstance().getTimeInMillis() = "+calendar.getTimeInMillis());
System.out.println("Calendar.getInstance().getTime().getTime() = "+calendar.getTime().getTime());
}
}
All the functions that you used in your example return the same value (if launched in the same millisecond) none of them is more accurate.
Once of them is not creating any object, so if you need only to know the current milliseconds since 1/1/1970 use
System.currentTimeMillis()
Instead if you need to have also the equivalent object to store that value or to make additional operations use the object that you need.
For example if you need to pass this value to a function accepting a java.util.Date use java.util.Date (and so on).

JAVA save several DATE into a LIST using a custom Datatype

I want to save several periods of time, which look like that:
public class periodOfTime {
Date from;
Date to;
}
into a List, which looks like that
List <periodOfTime> periodsOfTime = new List<periodOfTime>()
right now.
How can I store !FOR EXAMPLE!
Date s = new Date();
in my list?
My thoughts were, that it can be done with
periodsOfTime.add(s,s)
But it keeps on telling me
The method add(int, periodOfTime) in the type List is not applicable for the arguments (Date, Date)
Can anyone guide me?
Probably I am totally blind right now....
You may want to make getters and setters:)
Try:
PeriodOfTime period = new Period();
period.from = date;
period.to = another_date;
and add to for example ArrayList:
periodsOfTime.add(period);
It will help.

Why this piece of code is throwing classCastException

List<Object[]> arrayList = new ArrayList<Object[]>();
for(Object[] obj: arrayList)
{
// assuming at 0th location Timestamp value
Date dt = convertTimestampToDate((Timestamp)obj[0]) // Timestampvalue , '2013-09-11 00:00:0' throwing classCastException at this line
}
public static java.sql.Date convertTimestampToDate(java.sql.Timestamp timestamp) {
if(isNull(timestamp))
return null;
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new java.sql.Date(milliseconds);
}
Exception thrown is
You cannot cast java.lang.String to Timestamp
Here, I am assuming obj[0] is an object type and casting it to Timestamp
Any Ideas will be appreciable.
The exception is pretty self explanatory. In Java, everything is an Object (with the exception of primitives, but that's another subject). So, even though you've got an array of Objects, that doesn't mean you can arbitrarily cast those Objects to anything you want.
Date dt = convertTimestampToDate((Timestamp)obj[0])
obj[0] is clearly a String when you attempt that cast, and as such you will need to use SimpleDateFormat or similar to parse that String. You cannot cast a String to a Timestamp for the simple reason that Java doesn't (and can't) know how to do that.
You should convert the String object to Timestamp by using the Timestamp#valueOf(String s) method.
Change
Date dt = convertTimestampToDate((Timestamp)obj[0]) ;
to
Date dt = convertTimestampToDate(Timestamp.valueOf(obj[0].toString()));

Extracting data from a DateTime object

I'm working on a method that can tell me if a certain date is within a certain period of dates. My method will have an argument of two DateTime objects; a start date and end date, and will be called by a DateTime object as well.
To play around with it, I've been trying to figure out how to extract the year, month, day , time, from a DateTime object that is being compared to. However I can't figure out how to get it going. I checked the API for DateTime, and the method it has to perform the function I want is monthOfYear().
But when I implement it, it outputs "Property[monthOfYear]".
The API places the method under DateTime.Property but I played around with that too and I'm not getting anywhere.
import org.joda.time.DateTime;
public class Tester implements TesterInterface {
public static void main(String[] args) {
DateTime dateTime1 = new DateTime(2012, 5, 12, 13, 30);
System.out.println(dateTime1.monthOfYear());
}
}
Call getMonthOfYear().
As documented:
Each individual field can be queried in two ways:
getHourOfDay()
hourOfDay().get()
Change
dateTime1.monthOfYear()
to
dateTime1.getMonthOfYear()

Categories

Resources