Regarding jFreeChart's Millisecond,
How can I get a java.util.Date object from a Millisecond instance?
From the docs, it only seems possible to subtract the milliseconds within Millisecond.
Since a Millisecond object is constructed like so:
Millisecond ms = new Millisecond(
millisec,
second,
minute,
hour,
day,
month,
year);
I should be able to extract a valid Date object as well.
Edit
I need a Date object that gives back the exact time up to the millisecond accurate.
Does .getStart() provide this?
[ANSWER]: YES
Millisecond is like any other RegularTimePeriod in JFreeChart, so you can just
Date d = ms.getStart();
or
Date d = ms.getEnd();
depending on whether you want a date referring to the beginning or the end of your millisecond (same value either way).
See The JFreeChart API for more info.
EDIT: Adding code here since comments kill formatting:
Millisecond ms = new Millisecond();
System.out.println(ms.getStart().getTime());
System.out.println(ms.getEnd().getTime());
will print the same millisecond twice.
As far as I can see the Millisecond Class represents the time period of a millisecond and I'd assume the the getStart and getEnd Methods inherited from RegularTimePeriod return (nearly) the same Date of which one is one you're looking for.
(my answer was late) Perhaps you could use this code:
java.util.Date date = new java.util.Date(freeMillis.getMillisecond());
edit: scrap that, freeMillis.getMillisecond() returns just a millisecond part.
Related
I am taking data from a sql database and then displaying this data in the form of graphs. A graph I am making bases the data off of the time. I want to get rid of the seconds because it is useless for my application and takes up room.
I tried using a calender object to remove the seconds from it like this:
ArrayList<Time> ints3 = new ArrayList<Time>();
while ( rs.next() ){
ints3.add(rs.getTime(ints.get(0)));
}
Calendar instance = Calendar.getInstance();
instance.setTime(ints3.get(1));
instance.clear(Calendar.SECOND);
ints3.set(1, (Time) instance.getTime());
This did not work however because you can not cast a java.util date into a sql time. How can I go about removing the seconds part of the time.
The answer to your need (which is to symbolize the Date without displaying the seconds) is to use the DateFormat class. Given that Time is a java.sql.Time object, convert it to a Date first:
Date myDate=new Date(Time.getTime());
DateFormat df=new SimpleDateFormat("H:mm");
String myDateStr=df.format(myDate);
I'd like to comment this but I do not have enough reputation points. I believe this answer could help you
https://stackoverflow.com/a/21250071/2987444
You could use Jodatimes, methods to add/take away seconds and then convert back
This did not work however because you can not cast a java.util date into a sql time That's strange because java.sql.Time extends java.util.Date.
You're downcasting the result of Calendar#getTime but this won't work. Instead, create an instance of java.sql.Time and pass as parameter the time in millis:
//ints3.set(1, (Time) instance.getTime())
ints3.set(1, new Time(instance.getTime().getTime()));
Still, it will be way better to change ArrayList<Time> to List<Date> (java.util.Date).
Well you can use setTime method in Time class which accepts a long value that you can get by calling getTimeInMillis() of Calendar class(in your case after clearing seconds part).But even if you do that the Time object will take Hour,minute and the seconds part(with seconds part set to zero).If you don't want seconds part in the display then you can use concatenation of getHours and getMinutes methods of Time class.
This question already has answers here:
How to check if 2 dates are on the same day in Java
(4 answers)
Closed 8 years ago.
I have two calendar objects, they seems to contain same dates but the compareTo() method is returning -1 as result, Can any one explain the reason behind this.
On debugging the two Calendar objects, the result is shown as :
2014-06-01T00:00:00.000Z
for both calendar objects but the compareTo() is returning -1. Even the long time in millis for both dates are different.
Well, have a look at the Calendar code (this is from JDK 1.7.0-13):
public int compareTo(Calendar anotherCalendar) {
return compareTo(getMillisOf(anotherCalendar));
}
private int compareTo(long t) {
long thisTime = getMillisOf(this);
return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
}
It should be obvious that if the two Calendar's have different millis, then they're different as per the second method.
In any case, the millis in your example should not both represent 2014-06-01T00:00:00.000Z so there's another problem in your code. Try this:
Timestamp ts1 = new Timestamp( 1401561000000L );
Timestamp ts2 = new Timestamp( 1401595200000L );
System.err.println( ts1 );
System.err.println( ts2 );
Outputs:
2014-05-31 20:30:00.0
2014-06-01 06:00:00.0
Cheers,
The milliseconds number is the "offical" time in Java. However, for a variety or reasons, there are numbers with the same date/time which have different numbers of milliseconds. Then normal reason is clock adjustments. E.g. Sometimes you have to add a second or two to account for irregularities in the earth's orbit. The other big source is when regions were first brought into the UTC, then some time zones moved hours.
THere is also the common source for these things: DST.
This will happen twice a year when you move to daylight saving time, on the one hand there are date/times which do not exists, as they were "skipped", and there are other times which happened twice, as the clock gets reset at midnight, so 11pm-midnight happens twice on the same day.
If you want to just compare the minutes and ignore the milliseconds or seconds do this:
You need to use
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.
Quick explanation of what is going on:
The JavaDoc for Calendar states:
Compares the time values (millisecond offsets from the Epoch)
represented by two Calendar objects.
So you acknowledge that ".. long time in millis for both dates are different .."
#JonSkeet says in this question:
Calendar.setTime takes a java.util.Date, which is just a wrapper
around a long indicating the number of milliseconds since midnight Jan
1st 1970, UTC. It's not "in the format MM/dd/yyy" - that's a string
representation, not a java.util.Date. If it happens to print something
out in the format MM/dd/yyyy, that's just what Date.toString is doing
for you - it's not inherently part of the format.
This should answer your question about what is going on.
Note: java.util.Date has the same problem.
PS. A lot of people say use Joda Time, which I have heard is going to be in Java 8, but I have not personally tried it. If you are going to be using a lot of date code, I'd recommend you use it.
I invoked compareTo on Date instead of Calendar and got the correct result. It might be because of the fact that Calendar stores Timezone information but Date object does not.
Thanks
I'm making a basic Java program that reads in a subtitle (.srt) file and I would like to store each time as a Date object. I really only need to keep track of Hours, minutes, seconds, and milliseconds (to 3 digits). I think I am able to store it using this:
String start = "00:01:01,604";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss,SSS");
Date startDate = sdf.parse(start);
For retrieving, I can do something like this:
return String.format("\nStart: %d:%d:%dText: %s\n", startDate.getHours(),startDate.getMinutes(), startDate.getSeconds(), text);
I'm looking for something that would do something similar to getMilliseconds (if it existed). Thank you very much!
What you're handling is not a date! Don't use the Date class to handle it! Dates have strange extra rules that you don't care about and that could easily trip you up (just think of leap years, leap seconds and time zones).
You should either
use a long to hold the milliseconds and handle the calculation on your own (it's not so hard, you're not implementing a calendar) or
use an existing duration class such as the one from Joda Time.
The recommended way to get access to part of date (hours,minutes, etc.) in Java is now using Calendar.get(Calendar.MILISECONDS), see javadocs. In case of your code it would look like this:
Date startDate = sdf.parse(start);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int milliseconds = calendar.get(Calendar.MILISECONDS);
P.S. Please note that regarding to javadocs Date.getHours(),Date.getSeconds(), etc. methods are currently deprecated anyway. Don't use them :).
Just call date.getTime() and get milliseconds.
You can always use Date.getTime() for getting value in milliseconds. It will return a value in long format
I want to convert a LocalTime object to a java.sql.Time object.
java.sql.Time time = new java.sql.Time(new LocalTime(1,0,0,0).getMillisOfDay());
System.out.println(time); //20:00:00
The above code, instead of creating a Time object with a value equal to 01:00:00, creates an object with a time of 20:00:00. The local time is eastern time.
What steps should I take?
Time(..) accepts a timestamp starting from 1970. So you should pass that:
new Time(new LocalTime(...).toDateTimeToday().getMillis())
I consider the currently accepted answer to be incorrect. Although java.sql.Time implies that its date fields are set to 1970-1-1, this is not true. If you use the conversion
new java.sql.Time(new LocalTime(...).toDateTimeToday().getMillis())
then the internal millesecond representation of the java.sql.Time object will reflect today's date. This leads to unexpected behavior when comparing java.sql.Time objects.
Comparisons are performed on the millisecond value, and if the underlying dates are different, the time fields are irrelevant to the comparison result
A better method, is to explicitly work with the time-fields, using the deprecated constructor and methods in java.sql.Time:
LocalTime localTime = new LocalTime(1,0,0,0);
java.sql.Time sqlTime = new java.sql.Time(localTime.getHourOfDay(), localTime.getMinuteOfHour(), localTime.getSecondOfMinute())
Similarly, in the other direction
java.sql.Time sqlTime = new java.sql.Time(1,0,0);
LocalTime localTime = new LocalTime(sqlTime.getHours(), sqlTime.getMinues(), sqlTime.getSeconds());
This seems like a hole in the Joda Time API. Right now getLocalMillis() is protected, but that's exactly the method I'd want to use.
However, if you want to avoid deprecated methods, you can figure out time on January 1, 1970:
LocalTime lt = new LocalTime(1, 23, 45, 678);
long millis = lt.toDateTimeToday().withDate(1970, 1, 1).getMillis()
java.sql.Time time = new java.sql.Time(millis);
This seems to work. Interestingly, I tried figuring out the millis by multiplying the values of the fields out. That produced the right long value, but when I passed it to the Time constructor, something weird happened with the time zone. (I think, at least. The Time value ended up five hours before the value I passed in, and I'm on Eastern Daylight Time, so I think that's what happened.)
i found another way to convert the java.time.LocalTime to java.time.LocalTime
LocalTime localTime = LocalTime.now();
Time time = Time.valueOf(localTime);
Given millis since epoch, I want an instance with the fields Month, Date, Year filled out, with the hour minute seconds set to some default values.
What is an efficient way to do this?
I know that there are sql ways to do it but is there a way to do it in Java?
Just use:
new Calendar(new Date(msSinceEpoch));
where the ms is a long value.
Use either LocalDate or DateMidnight in the Joda-Time API. The differences are explained in the javadocs.
Note that in order to truncate a point in time (some millis since epoch) to a specific calendar day, you might want to specify when midnight happened, or else you'll end up with midnight in the system's timezone. For example, you might call the LocalDate(long, DateTimeZone) constructor instead of the LocalDate(long) constructor.
Or, if you'd rather not have a JODA dependency, use DateFormat:
Date thisDate = new SimpleDateFormat("yyyy-MMM-dd").parse("2011-Jun-29");
Per the javadocs, you can easily create a Date from a long:
long value = System.currentTimeMillis();
Date thisDate = new Date(value);