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);
Related
I'm trying to convert a java.time.LocalTime object to java.util.Date but can't find any suitable method. What's the correct way to do this?
Is there any reason why java doesn't seem to ship with a built-in direct conversion method?
To possible duplicates:
How to convert joda time - Doesn't work for me, probably I'm missing some "joda" libraries?
How to convert Date to LocalTime? - This adresses conversion the other way around.
LocalTime actually can't be converted to a Date, because it only contains the time part of DateTime. Like 11:00. But no day is known. You have to supply it manually:
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
Here's a blog post which explains all the conversions between the new and the old API.
There's no simple built-in conversion method, because these APIs approach the idea of date and time in completely different way.
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
From :
http://blog.progs.be/542/date-to-java-time
I added the data (hour, minute, second) one by one (from localtime to date):
reta.setHours(vol.getRetard().getHour());
reta.setMinutes(vol.getRetard().getMinute());
reta.setSeconds(vol.getRetard().getSecond());
Note :
reta: Date veriabble ;
vol.getRetard (): localtime variable
As others have said, it’s a problematic question in that a LocalTime and a Date really represent quite different and almost unrelated concepts. A LocalTime is a time of day without time zone, such as 19:45 (or 7:45 PM). A Date is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones.
I believe that the conventional way of misusing (indeed) a Date for an hour of day is setting it to that time of day on January 1, 1970 in the default time zone of the JVM. This practice carries all of the liabilities already mentioned. In particular the JVM default time zone setting can be changed at any time from another part of your program or any other program running in the same JVM. This means that a completely unrelated program may suddenly cause your Date to indicate a different time of day than the one you had initialized it to.
There’s nothing better we can do, so here goes:
LocalTime time = LocalTime.of(11, 0);
Instant timeOnEpochDayInDefaultTimeZone = LocalDate.EPOCH
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant();
Date oldfashionedDateObject = Date.from(timeOnEpochDayInDefaultTimeZone);
System.out.println(oldfashionedDateObject);
In my time zone output from this snippet is:
Thu Jan 01 11:00:00 CET 1970
Here is another approach:
We can add a LocalDate to the LocalTime in order to make it a LocalDateTime and then convert it to Date using the valueOf method of java.sql.Timestamp like this:
LocalTime localTime = LocalTime.now();
Date date = java.sql.Timestamp.valueOf(localTime.atDate(LocalDate.now()));
As #Dariusz said, we cannot convert LocalTime to Date directly as it contains only time part but Date must contain all the value along with the timeZone.
In order to get the date part, we can use LocalDate.now(). It will give us LocalDate object with today's date.
Now, we have both LocalDate and LocalTime, we can now use the LocalDateTime.of(date: LocalDate, time: LocalTime) or localTime.atDate(date: LocalDate) to get the LocalDateTime object.
And now we can convert the LocalDateTime to Date using below kotlin extension function.
fun LocalDateTime.toDate(): Date {
return Date.from(this.atZone(ZoneId.systemDefault()).toInstant())
}
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.
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 need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possible. I was reading some other answers on here, but they all seem too sophisticated.
You could use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
Date date = calendar.getTime();
java.time
Using java.time framework built into Java 8
import java.time.YearMonth;
int year = 2015;
int month = 12;
YearMonth.of(year,month); // 2015-12
from String
YearMonth.parse("2015-12"); // 2015-12
with custom DateTimeFormatter
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy");
YearMonth.parse("12 2015", formatter); // 2015-12
Conversions
To convert YearMonth to more standard date representation which is LocalDate.
LocalDate startMonth = date.atDay(1); //2015-12-01
LocalDate endMonth = date.atEndOfMonth(); //2015-12-31
Possibly a non-answer since you asked for a java.util.Date, but it seems like a good opportunity to point out that most work with dates and times and calendars in Java should probably be done with the Joda-Time library, in which case
new LocalDate(year, month, 1)
comes to mind.
Joda-Time has a number of other nice things regarding days of the month. For example if you wanted to know the first day of the current month, you can write
LocalDate firstOfThisMonth = new LocalDate().withDayOfMonth(1);
In your comment you ask about passing a string to the java.util.Date constructor, for example:
new Date("2012-09-19")
This version of the constructor is deprecated, so don't use it. You should create a date formatter and call parse. This is good advice because you will probably have year and month as integer values, and will need to make a good string, properly padded and delimited and all that, which is incredibly hard to get right in all cases. For that reason use the date formatter which knows how to take care of all that stuff perfectly.
Other earlier answers showed how to do this.
Like
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
Date utilDate = formatter.parse(year + "/" + month);
Copied from Create a java.util.Date Object from a Year, Month, Day Forma
or maybe like
DateTime aDate = new DateTime(year, month, 1, 0, 0, 0);
Copied from What's the Right Way to Create a Date in Java?
The most common sense approach would be to use the Date("YYYY-MM-DD") constructor even though it is deprecated. This is the easiest way to create a date on the fly. Screw whoever decided to deprecate it. Long live Date("YYYY-MM-DD")!!!
Don’t use this answer. Use the answers by Przemek and Ray Toel. As Przemek says, prefer to use a YearMonth for representing year and month. As both say, if you must use a date, use LocalDate, it’s a date without time of day.
If you absolutely indispensably need an old-fashioned java.util.Date object for a legacy API that you cannot change, here’s one easy way to get one. It may not work as desired, it may not give you exactly the date that you need, it depends on your exact requirements.
YearMonth expiration = YearMonth.of(2021, 8); // or .of(2021, Month.AUGUST);
Date oldFashionedDateObject = Date.from(expiration
.atDay(1)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(oldFashionedDateObject);
On my computer this prints
Sun Aug 01 00:00:00 CEST 2021
What we got is the first of the month at midnight in my local time zone — more precisely, my JVM’s time zone setting. This is one good guess at what your legacy API expects, but it is also dangerous. The JVM’s time zone setting may be changed under our feet by other parts of the program or by other programs running in the same JVM. In other words, we cannot really be sure what we get.
The time zone issue gets even worse if the date is transmitted to a computer running a different time zone, like from client to server or vice versa, or to a database running its own time zone. There’s about 50 % risk that your Date will come through as a time in the previous month.
If you know the time zone required in the end, it will help to specify for example ZoneId.of("America/New_York") instead of the system default in the above snippet.
If your API is lenient and just needs some point within the correct month, you’ll be better off giving it the 2nd of the month UTC or the 3rd of the month in your own time zone. Here’s how to do the former:
Date oldFashionedDateObject = Date.from(expiration
.atDay(2)
.atStartOfDay(ZoneOffset.UTC)
.toInstant());
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);