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).
Related
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.
So I am trying to create a program that helps me keep track of my expenses and i have a question to do with how I create my objects.
So far i have been creating my objects like so:
Grocery milk = new Grocery();
milk.setName("Milk");
milk.setCost(2.84);
milk.setDate(30, 12, 2014);
milk.setType("Food");
My grocery class extends this expense class:
public Expense(){}
public Expense(String name, Double cost, Calendar purchaseDate){
name = _name;
cost = _cost;
purchaseDate = _purchaseDate;
}
So far my grocery class only adds another string parameter that i call type, and so here is my question:
Instead of using set methods to set my paramters for each new created object i would like to do it like this:
Grocery milk = new Grocery("Milk", 2.84, ??Date??, "Food")
But the date parameter is a little more complicated than the other parameters that are just of type string and double, is there a way to do what I want or am i better off using the set methods?
Thanks in advance for any help.
You can simply use an Object of type Date
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("16/01/2015");
Grocery milk = new Grocery("Milk", 2.84, date, "Food")
Alternatives include using a Calendar object (which has more flexible/powerful date manipulation methods), or just storing your date as a String.
As for deciding whether you should use setX() methods or using a comprehensive constructor, unless there is a reason not to you can just have both available, and just use the most suitable at any one time.
Further reading:
Official Java Date & Time tutorials
Official Java Calendar tutorials
I'm calling in JS some javaMethod(java.util.Date date).
I can't change code on java-side. How can I create java.util.Date object from JS-side (at least empty date)?
There is no way to use java date in javascript use javascript Date
var date = new Date();
Just get the long value from javascript date and pass to java.
in javascript get time in milliseconds as
var timeinmillis = new Date().getTime();
and pass this to java.
in java , look at the constructor
public Date(long date)
Solved it in a not very good way, but still..
So now I'm just added to that method with JS just one more Date arg.
Now it looks like
native void doSomething(Object object, Date date) /*-{
.....
.....::setDate(Ljava/util/Date;)(date);
.....
}-*/;
and calling it like doSomething(var1, new Date());
I wonder why the setTime method behaves exactly like setDate, date without time, or instead to set the time on 2014-07-01 13:21:01 it is set on 2014-07-01 00:00:00 ?!?!
Is setTime deprecated?
Should I use setTimestamp???
Databases other than Oracle actually do distinguish between three different datatypes:
DATE only date, no time
TIME only time of the day, no date
TIMESTAMP both, date & time.
JDBC tries to abstract standard SQL concepts and the above three datatypes are defined by ANSI SQL and thus JDBC needs to support them.
As Oracle's date always includes the time, you have to use setTimestamp() otherwise the time is lost when you store it in the database.
setTime() Method :
The java.util.Calendar.setTime(Date) method sets Calendar's time with the given Date.
Following is the declaration for java.util.Calendar.setTime() method
public final void setTime(Date date)
This method does not return a value.
Example :
The following example shows the usage of java.util.calendar.setTime() method.
package com.tutorialspoint;
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create a calendar
Calendar cal = Calendar.getInstance();
// get the current time
System.out.println("Current time is :" + cal.getTime());
// create new date and set it
Date date = new Date(95, 10, 10);
cal.setTime(date);
// print the new time
System.out.println("After setting Time: " + cal.getTime());
}
}
SetTimestamp Method :
Sets the designated parameter to the given timestamp and calendar values.
Syntax
public void setTimestamp(java.lang.String sCol,
java.sql.Timestamp x,
java.util.Calendar c)
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()