System.currentTimeMillis() for a given date? [duplicate] - java

This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 6 years ago.
Since java.util.Date is mostly deprecated, what's the right way to get a timestamp for a given date, UTC time? The one that could be compared against System.currentTimeMillis().

Using the Calendar class you can create a time stamp at a specific time in a specific timezone. Once you have that, you can then get the millisecond time stamp to compare with:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, 10);
// etc...
if (System.currentTimeMillis() < cal.getTimeInMillis()) {
// do your stuff
}
edit: changed to use more direct method to get time in milliseconds from Calendar instance. Thanks Outlaw Programmer

The "official" replacement for many things Date was used for is Calendar. Unfortunately it is rather clumsy and over-engineered. Your problem can be solved like this:
long currentMillis = System.currentTimeMillis();
Date date = new Date(currentMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long calendarMillis = calendar.getTimeInMillis();
assert currentMillis == calendarMillis;
Calendars can also be initialized in different ways, even one field at a time (hour, minute, second, etc.). Have a look at the Javadoc.

Although I didn't try it myself, I believe you should take a look at the JODA-Time project (open source) if your project allows external libs.
AFAIK, JODA time has contributed a lot to a new JSR (normally in Java7) on date/time.
Many people claim JODA time is the solution to all java.util.Date/Calendar problems;-)
Definitely worth a try.

Take a look at the Calendar class.
You can make a Data with the current time (not deprecated) and then make Calendar from that (there are other ways too).

Related

Using instances of GregorianCalendar to determine time passed?

I am working on a project in my CIS 163 class that is effectively a campsite reservation system. The bulk of the code was provided and I just have to add certain functionalities to it. Currently I need to be able to determine how much time has passed between 2 different GregorianCalendar instances (one being the current date, the other being a predetermined "check out") represented by days. I haven't been able to figure out quite how to do this, and was hoping someone here might be able to help me out.
The GregorianCalendar is old and you shouldn't really use it anymore. It was cumbersome and was replaced by the "new" java.time module since Java 8.
Still, if you need to compare using GC instances, you could easily calculate time using milliseconds between dates, like this:
GregorianCalendar date1 = new GregorianCalendar();
GregorianCalendar date2 = new GregorianCalendar();
// Adding 15 days after the first date
date2.add(GregorianCalendar.DAY_OF_MONTH, 15);
long duration = (date2.getTimeInMillis() - date1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
If you want to use the new Time API, the following code would work.
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(15);
Period period = Period.between(date1, date2);
int diff = period.getDays();
System.out.println(diff);
If you need to convert between the types (e.g. you're working with legacy code), you can do it like this:
LocalDate date3 = gcDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate date4 = gcDate2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Also I'm pretty sure this question must've been asked over and over again, so make sure you search properly before asking.
Since you have been forced to use the old and poorly designed GregorianCalendar class, the first thing you should do is convert each of the two GregorianCalendar objects to a modern type. Since Java 8 GregorianCalendar has a method that converts it to ZonedDateTime. Check the documentation, I include a link below.
Now that you’ve got two ZonedDateTime objects, there are different paths depending on your exact requirements. Often one will use Duration.between() for finding the duration, the amount of time between them in hours, minutes, seconds and fraction of second. If you know that you will always need just one of those time units, you may instead use for example ChronoUnit.HOURS.between() or ChronoUnit.MILLISECONDS.between(). If you need to count days, use ChronoUnit.DAYS.between().
If instead you need the time in months and days, you should instead use Period.between().
Links
Documentation:
GregorianCalendar (long outdated, don’t use unless forced to)
Duration
ChronoUnit
Period
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API to which ZonedDateTIme, Duration, ChronoUnit and Period belong.

In which type of variable store time in millis? Choosing a correct data type

in Java I'm trying to compare two different hours by converting them to milliseconds if (20:00 > 19:30) // do anything. In millis, it would be if (72000000 > 70200000) // do anything
But the smartphone doesn't do it well. I'm storing the numbers in variables long, as in the class Calendar, the method myCal.getTimeInMillis() returns a long, but it doesn't work.
I have tried changing the data type of the variables from long to double and it does work, so I figure out that those large numbers simply "doesn't fit" in the variable, but then, why the Java Calendar method getTimeInMillis() returns a long?
How does time work in Java Calendar? Thanks in advance.
Edit:
Thank you for your answers and time, I'm sorry for this question because it does work to compare different hours which are stored in long variables. I have tried again and it does work (I don't know why it didn't work before). I'm making an alarm clock app for Android and I want to compare not only two hours (and minutes and seconds), but also day of the week and so on. So I'm going to mark as the solution of this question the answer of #Sufiyan Ghori because I think it can really help me, and I think I'm gonna delete this question because it has no sense.
I'm new here (and in programming in general), so sorry for this silly question.
instead of comparing hours after converting it into milliseconds you can use Date::before or Date::after methods after setting your time into two separate Date objects.
Date date1 = new Date(); // set time for first hour.
Date date2 = new Date(); // set time for second hour.
You can use Calendar to set time for each Date object, like this,
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,12);
cal.set(Calendar.MINUTE,10);
cal.set(Calendar.SECOND,31);
cal.set(Calendar.MILLISECOND,05);
date1 = cal.getTime(); //set time for first hour
and then use these for comparison,
if(date1.after(date2)){
}
if(date1.before(date2)){
}
and Date::equals,
if(date1.equals(date2)){
}
getTimeInMillis() doesn't return milliseconds passed from the start of the current day, it returns millisecons passed since 01 Jan 1970 00:00:00 GMT.
Take a look at documentation of Calendar class: java.util.Calendar

Update time only

Is there any way to update only a Date's time path?
I tried Date.setTime() but it replaces the date path too. I there any java method or the only way is to set hour, minute, second and milisecond?
Thank you
A Java Date is just a wrapper around a long that counts time from the epoch (January 1, 1970). Much more flexible is Calendar. You can create a Calendar from a Date:
Date date = . . .;
Calendar cal = new GregorianCalendar();
cal.setTime(date);
Then you can set various fields of the Calendar:
cal.set(Calendar.HOUR_OF_DAY, 8);
// etc.
I would start by moving away from java.util.Date entirely. Ideally, use Joda Time as it's a far more capable date/time library.
Otherwise, you should use java.util.Calendar. A java.util.Date doesn't have a particular date/time until you decide what time zone you're interested in - it just represents an instant in time, which different people around the world will consider to be a different date and time of day.
You'll want to take a look at java.util.Calender.
It will allow you to change the individual parts of the date/time.
Calendar cal = Calender.getInstance();
cal.setTime(date);
cal.set(Calender.HOUR, hour);
Alternatively, as has already being suggested, I'd take a look at Joda Time

Get Date as of 4 hours ago [duplicate]

This question already has answers here:
How to create a Date object, using UTC, at a specific time in the past?
(2 answers)
Closed 5 years ago.
How can I return a Date object of 4 hours less than the current system time in Java?
If you're already on Java 8 or newer:
LocalDateTime fourHoursAgo = LocalDateTime.now().minusHours(4);
Or if you want to take DST (Daylight Saving Time) into account (just in case it coincidentally went into or out DST somewhere the last 4 hours):
ZonedDateTime fourHoursAgo = ZonedDateTime.now().minusHours(4);
Or if you're not on Java 8 yet:
Date fourHoursAgo = new Date(System.currentTimeMillis() - (4 * 60 * 60 * 1000));
And you want to take DST into account:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
Date fourHoursAgo = calendar.getTime();
The other answers are correct, but I would like to contribute the modern answer. The modern solution uses java.time, the modern Java date and time API.
Instant fourHoursAgo = Instant.now().minus(Duration.ofHours(4));
System.out.println(fourHoursAgo);
This just printed:
2018-01-31T15:22:21.113710Z
The Z in the end indicates that the time is printed in UTC — at UTC offset zero if you will. The Instant class is the modern replacement for Date, so I recommend you stick to it. The modern API is generally so much nicer to work with, so much cleaner, so much better designed.
Please note the advantages of letting the library class do the subtraction of 4 hours for you: the code is clearer to read and less error-prone. No funny constants, and no readers taking time to check if they are correct.
If you do need an old-fashioned Date object, for example when using a legacy API that you cannot change or don’t want to change, convert like this:
Date oldfashionedDate = Date.from(fourHoursAgo);
Link: Oracle Tutorial trail: Date Time. Of course there are other resources on the internet too, please search.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
calendar.getTime();
Convert it to milliseconds, subtract the number of milliseconds in 4 hours, convert it back to a Date.
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -4);
java.util.Date d = c.getTime();
System.out.println(d);
Calendar c =Calendar.getInstance() ;
c.add(Calendar.HOUR,-4);
Date d = c.getTime();
Use a Calendar object and the add method.
calendar.add(Calendar.HOUR, -4);
See http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html

Construct Date - An efficient way

May I know what is the most efficient way to construct a date object using a specific day, month, and year.
Date(int year, int month, int day)
This construct is depreciated. Hence, what I usually do is:
Calendar calendar = Calendar.getInstance();
Date date = calendar.set(year, month, date).getTime();
However, my understanding is that Calendar.getInstance() is rather expensive. What is the most efficient way to construct a Date object? Or should I just use Date(int year, int month, int day) quietly without telling the rest?
Please don't suggest using any third-party library.
With this you can avoid the innecesary "now time" instance creation.
Date coolDate = new GregorianCalendar(year, month, day).getTime();
You can check GregorianCalendar javadoc for other constructors. You have date+time, and timezone.
Anyway I agree with Jon Skeet that it's not so expensive. I agree with you that code doesn't need a default "now" initialization.
"Rather expensive" is somewhat vague. Have you actually tried using the code you've supplied, measured it and found it to be too expensive? Do you have a concrete idea of how cheap you need this operation to be?
Also, you haven't specified which time zone you want the value in the Date to represent. UTC? The default time zone? What time of day do you want it to be - midnight, or the current time of day? Your current code will keep the existing time of day - is that really what you want?
(As I mentioned in a comment, I would strongly suggest you move to Joda Time - but even if you don't, you should still check whether or not you've actually got a problem with your existing code before looking for a solution.)
I would simply do this:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date thisDate = formatter.parse("2010-03-04");
It's pretty efficient from a lines of code standpoint; I can't speak to its runtime efficiency vis a vis Calendar.
Ten years later in 2020: the only right answer is to use classes in java.util.time package.
LocalDate localDate = LocalDate.now();
LocalDate.of(2020, 3, 7);
LocalDate.parse("2020-03-07");
Whatever you use, as long as it's in the Java Standard API, it will involve the use of Calendar (both the Date constructor and SimpleDateFormat use it internally), so there's no point fretting about that class's supposed inefficiency.

Categories

Resources