Getting hours,minutes, and seconds from Date? [duplicate] - java

This question already has answers here:
Java: getMinutes and getHours
(13 answers)
Closed 8 years ago.
I want to get the current hour,minute, and second from the Date object.
This is my code:
Date date = new Date();
int hour = date.getHours();
But I get a kind of error, the getHours() part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?

Use Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
From Date javadoc:
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

Related

Android/Java Difference between 2 dates in days [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 12 months ago.
So I'm having some issues in trying to do this, I already tried with this code:
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
And I kinda know why this is not what I want because, the thing that I need is taking the first date that I insert in database, and I want that to be like (CURRENTDATE - TXTDATE == DAYS THAT LEFT)
Maybe try this:
public long daysBetween(Calendar startDate, Calendar endDate) {
return TimeUnit.MILLISECONDS.toDays(Math.abs(endDate.getTimeInMillis() - startDate.getTimeInMillis()));
}

Why there is a difference between GregorianCalendar.getTimeInMillis() and GregorianCalendargetTimeInMillis(1970.01.01)) [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));

Subtracting 5 minutes from epoch date [duplicate]

This question already has answers here:
subtracting two days from current date in epoch milliseconds java [duplicate]
(5 answers)
Closed 8 years ago.
What is the best way to subtract 5 minutes from a given epoch date ?
public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}
epochDate has to be a Date. Use a Calendar:
Calendar calendar = Calendar.getInstance();
calendar.setTime(epochDate);
calendar.add(Calendar.MINUTE, -5);
Date result = calendar.getTime();
You can use any of the above mentioned methods by other user , but if interested give a try to
Java 8 Date and Time API
public void subtract_minutes_from_date_in_java8 ()
{
LocalDateTime newYearsDay = LocalDateTime.of(2015, Month.JANUARY, 1, 0, 0);
LocalDateTime newYearsEve = newYearsDay.minusMinutes(1);// In your case use 5 here
java.time.format.DateTimeFormatter formatter =java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(newYearsDay.format(formatter));
logger.info(newYearsEve.format(formatter));
}
Output :
01/01/2015 00:00:00 CST
12/31/2014 23:59:00 CST
Class LocalDateTime is an immutable date-time object present in java.time package in Java 8 that represents a date-time, often viewed as year-month-day-hour-minute-second.
Below is the syntax of of() method used :
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
which obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
You can subtract 5 minute equivalent of miiliseconds from date you get:-
//convert input string epochDate to Date object based on the format
long ms=date.getTime();
Date updatedDate=new Date(ms - (5 * 60000)); //60000 is 1 minute equivalent in milliseconds
return updatedDate.getTime();
Here's a body for your method:
private static final long FIVE_MINS_IN_MILLIS = 5 * 60 * 1000;
public long fiveMinutesAgo(String epochDate) throws ParseException {
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
long time = df.parse(epochDate).getTime();
return time - FIVE_MINS_IN_MILLIS;
}
The time is in millis-since-the-epoch, so to find out five minutes before you simply have to subtract 5 mins in milliseconds (5 * 60 * 1000).
I would suggest renaming the method to: fiveMinutesBefore() and perhaps breaking it into two methods: one for parsing string dates into times and the other for subtracting minutes from the time.
You might also consider using Joda-Time as it's much better designed (and thread-safer) than the standard Java date package.

Random date for year 2014 java [duplicate]

This question already has answers here:
Generate random date of birth
(15 answers)
Closed 8 years ago.
I want to generate a random date as string in format - yy-MM-dd for the given year.
assume if i pass the year it should give a random date of the year.
I went through Random() as well as nextInt() but not sure how to get this
could you please help me on how to achieve this?
Thanks.
You can use a Calendar to do that:
final Calendar cal = Calendar.getInstance();
final Random rand = new Random();
final SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, rand.nextInt(cal.getActualMaximum(Calendar.DAY_OF_YEAR)) + 1);
System.out.println(format.format(cal.getTime()));
cal.getActualMaximum(Calendar.DAY_OF_YEAR) will return the number of the last day of the year the Calendar is set to (2014 in this code).
rand.nextInt() will return a number between 0 (inclusive) and the number of the last day (exclusive). You have to add 1 because the field Calendar.DAY_OF_YEAR starts at 1.
cal.set() will set the given field of the Calendar to the value given as the second argument. It is used here to set the year to 2014, and the day of the year to the random value.
SimpleDateFormat is used to print the date in the required format.
You can do with JSR-310 (Built in Java 8, but available to older versions)
public static LocalDate randomDateIn(int year) {
Year y = Year.of(year);
return y.atDay(1+new Random().nextInt(y.length()));
}
System.out.println(randomDateIn(2014));
prints something like
2014-05-21
If you want to work with random, this is how it works:
Random r=new Random();
int day=r.nextInt(30)+1; // (think of something yourself for implementing months with different amount of days)
int month=r.nextInt(11)+1; // (+1 because you don't want the zero)
However i see another answer, which if it works will probably save you a lot of time on implementing the days each month has.(and the leap year)

How to add or subtract 3 days from currentdate in java? [duplicate]

This question already has answers here:
How to add one day to a date? [duplicate]
(18 answers)
Closed 9 years ago.
I need to subtract 3 days from current date and need to store that in Date variable?
You could do this
Calender c = Calender.getInstance();
c.add(DAY_OF_MONTH,3);
c.add(DAY_OF_MONTH,-3);
Date d = c.getTime();
Pull the milliseconds-since-epoch value out, subtract three days of milliseconds from it, shove it into a new Date object.
public static final long ONE_DAY_MILLIS = 86400 * 1000;
Date now = new Date();
Date then = new Date(now.getTime() - (3 * ONE_DAY_MILLIS));

Categories

Resources