Creating Java Date Object from Year,Month,Day

Creating java date object from year,month,day

Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use

c.set(year, month - 1, day, 0, 0);  

How to get a Date object from year,month and day?

Without knowing more I'd have to guess but probably you didn't read the JavaDoc on that deprecated constructor:

year the year minus 1900.

month the month between 0-11.

date the day of the month between 1-31.

As you can see, if you want to create a date for today (Aug 5th 2015) you'd need to use new Date (115, 7, 5);

If you see that documentation you are free to guess why this is deprecated and should not be used in any new code. :)

create Date object from year, month, day AND time

You are using Date#getYear wrongly:

Returns a value that is the result of subtracting 1900 from the year
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone.

getYear() has an offset of 1900, which you have to add when using LocalDate.of(year, month, day). That's why the year of your calculated Instant is 115.

Instant instant = time.atDate(LocalDate.of(date.getYear() + 1900,
date.getMonth(), date.getDay())).atZone(ZoneId.systemDefault()).toInstant();

I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?

Use something like:

Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.

Beware, months start at 0, not 1.

Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.

javascript create date from year, month, day

According to MDN - Date:

month

Integer value representing the month, beginning with 0 for
January to 11 for December.

You should subtract 1 from your month:

const d = new Date(2016, 11, 17, 0, 0, 0, 0);

How to generate a Date from just Month and Year in Java?

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 - Format a date given day, month and year integers

If you're concerned about garbage collecting and objects creation, why not keep a single Calendar instance in your class or system, and use it for all formatting purposes using a static / synchronized method?



Related Topics



Leave a reply



Submit