I am beginning Java and I have been ask to write a class myDate. Such a class has fields for year, month and day.
I should use the following syntax to set the date:
setDate(long timeElapsed)
I know that I can do the following:
Date tempDate = new Date();
long lngDate = tempDate.getTime();
System.out.println("lngDate: " + lngDate);
How do I calculate the "long timeElapsed" parameter from a given year, month and day?
Now, I should use GregorianCalendar to display the date, for which I have done the following:
GregorianCalendar cal = new GregorianCalendar(year, month, day);
System.out.println("Year: " + cal.YEAR);
System.out.println("Month: " + cal.MONTH);
System.out.println("Day: " + cal.DAY_OF_MONTH);
But the results I get are as follow:
Year: 1
Month: 2
Day: 5
How can I use GregorianCalendar to display a date in myDate class? I have been working on this issue for a while without success.
I will very much appreciate your feedback.
Respectfully,
Jorge Maldonado
Calendar.YEAR as well as MONTH and DAY_OF_THE_MONTH are constants to use in get() method. so
System.out.println("Year: " + cal.get(Calendar.YEAR));
System.out.println("Month: " + cal.get(Calendar.MONTH));
System.out.println("Day: " + cal.get(Calendar.DAY_OF_MONTH));
does what you need.
BTW on top you do not need to create new Date to get time value:
long lngDate = System.currentTimeMillis();
System.out.println("lngDate: " + lngDate);
value is the same. When new Date created it uses System.currentTimeMillis()
PS. Just keep in mind cal.get(Calendar.MONTH) returns month number -1. Jan is month 0, Feb is month 1 and so on.
Just call the following method to get the date as a long from a calendar:
cal.getTimeInMillis()
Here is the corresponding class:
public class MyDate {
public void setDate(long timeElapsed) {
final GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(timeElapsed));
this.year = cal.get(Calendar.YEAR);
this.month = cal.get(Calendar.MONTH);
this.day = cal.get(Calendar.DAY_OF_MONTH);
}
public long getLong() {
final GregorianCalendar cal = new GregorianCalendar(this.year, this.month, this.day);
return cal.getTimeInMillis();
}
private int year, month, day;
}
Related
I was trying to compute week of year from a ISO-8601 Date format String input. Initially I tried this with java.time.ZonedDateTime but it gives incorrect result for Input Date - 2-Jan-2049. Then I tried with Calendar API it also gives incorrect response for 31-Dec-2049.
I have attached the sample test code
public class ZonedDateTimeTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("======================================");
String instantStr1 = "2049-01-02T03:48:00Z";
printYearAndWeekOfYear(instantStr1);
System.out.println("======================================");
String instantStr2 = "2049-12-31T03:48:00Z";
printYearAndWeekOfYear(instantStr2);
System.out.println("======================================");
}
public static void printYearAndWeekOfYear(String ISODate) {
System.out.println("Date provided -> " + ISODate);
ZonedDateTime utcTimestamp = parseToInstant(ISODate).atZone(ZoneOffset.UTC);
int year = utcTimestamp.getYear();
int weekOfYear = utcTimestamp.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
System.out.println("Using ZonedDateTime API:: Year " + year + " weekOfYear " + weekOfYear);
Date d1 = Date.from(parseToInstant(ISODate));
Calendar cl = Calendar.getInstance();
cl.setTime(d1);
int year1 = cl.get(Calendar.YEAR);
int weekOfYear1 = cl.get(Calendar.WEEK_OF_YEAR);
System.out.println("Using Calendar API:: Year " + year1 + " weekOfYear " + weekOfYear1);
}
public static Instant parseToInstant(String ISODate) {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(ISODate, Instant::from);
}
}
Output from code above
======================================
Date provided 2049-01-02T03:48:00Z
Using ZonedDateTime API: Year 2049 weekOfYear 53
Using Calendar API: Year 2049 weekOfYear 1
======================================
Date provided 2049-12-31T03:48:00Z
Using ZonedDateTime API: Year 2049 weekOfYear 52
Using Calendar API: Year 2049 weekOfYear 1
======================================
There are four problems with your code to start with:
You're using the system default time zone when you use Calendar, which may well change which date the Instant falls on. If you set the calendar to use UTC you'll make it more consistent.
You're using Calendar.YEAR which will give you the calendar year rather than the week year. You need to use Calendar.getWeekYear() instead.
You're using ZonedDateTime.getYear() which is again the calendar year. You shuold be using utcTimestamp.get(IsoFields.WEEK_BASED_YEAR)
You're using Calendar.getInstance() which could give you a non-Gregorian calendar, or it could have first-day-of-week set inappropriately for the computation you want to perform
Fixing these issues (and naming conventions) we end up with:
import java.util.*;
import java.time.*;
import java.time.format.*;
import java.time.chrono.*;
import java.time.temporal.*;
public class ZonedDateTimeTest {
public static void main(String[] args) {
printYearAndWeekOfYear("2049-01-02T03:48:00Z");
String instantStr2 = "2049-12-31T03:48:00Z";
printYearAndWeekOfYear("2049-12-31T03:48:00Z");
}
public static void printYearAndWeekOfYear(String isoDate) {
System.out.println("Date provided -> " + isoDate);
Instant instant = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(isoDate, Instant::from);
ZonedDateTime utcTimestamp = instant.atZone(ZoneOffset.UTC);
int year = utcTimestamp.get(IsoFields.WEEK_BASED_YEAR);
int weekOfYear = utcTimestamp.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
System.out.println("ZonedDateTime: Year " + year + " weekOfYear " + weekOfYear);
// Force the Gregorian calendar with ISO rules and using UTC
Calendar calendar = new GregorianCalendar();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(Date.from(instant));
int calYear = calendar.getWeekYear();
int calWeekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("Calendar: Year " + calYear + " weekOfYear " + calWeekOfYear);
System.out.println();
}
}
Output:
Date provided -> 2049-01-02T03:48:00Z
ZonedDateTime: Year 2048 weekOfYear 53
Calendar: Year 2048 weekOfYear 53
Date provided -> 2049-12-31T03:48:00Z
ZonedDateTime: Year 2049 weekOfYear 52
Calendar: Year 2049 weekOfYear 52
Both of those look good to me.
The old Calendar-stuff indeed enables a solution since Java-7 so I show it as supplement to the Java-8-related answer of Jon Skeet:
String instantStr1 = "2049-01-02T03:48:00Z";
String instantStr2 = "2049-12-31T03:48:00Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date d1 = sdf.parse(instantStr1);
Date d2 = sdf.parse(instantStr2);
GregorianCalendar gcal = new GregorianCalendar();
gcal.setFirstDayOfWeek(Calendar.MONDAY);
gcal.setMinimalDaysInFirstWeek(4);
gcal.setTime(d1);
System.out.println(
"Using Calendar API: Year " + gcal.getWeekYear() + " weekOfYear "
+ gcal.get(Calendar.WEEK_OF_YEAR)
); // Using Calendar API: Year 2048 weekOfYear 53
gcal.setTime(d2);
System.out.println(
"Using Calendar API: Year " + gcal.getWeekYear() + " weekOfYear "
+ gcal.get(Calendar.WEEK_OF_YEAR)
); // Using Calendar API: Year 2049 weekOfYear 52
For Android-users where this API is standard: The method getWeekYear() is available since API-level 24.
I am using the below code
#SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
I am getting below output.
3914-02-09
39140209
Does any one know why there is 3914?
Thanks,
Mahesh
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09
I need to check if a given date falls in the current month, and I wrote the following code, but the IDE reminded me that the getMonth() and getYear() methods are obsolete. I was wondering how to do the same thing in newer Java 7 or Java 8.
private boolean inCurrentMonth(Date givenDate) {
Date today = new Date();
return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}
//Create 2 instances of Calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//set the given date in one of the instance and current date in the other
cal1.setTime(givenDate);
cal2.setTime(new Date());
//now compare the dates using methods on Calendar
if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
if(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
// the date falls in current month
}
}
java.time (Java 8)
There are several ways to do it with the new java.time API (tutorial). You can do it using .get(ChronoField.XY), but I think this is prettier:
Instant given = givenDate.toInstant();
Instant ref = Instant.now();
return Month.from(given) == Month.from(ref) && Year.from(given).equals(Year.from(ref));
For better re-usability you can also refactor this code to "temporal query":
public class TemporalQueries {
//TemporalQuery<R> { R queryFrom(TemporalAccessor temporal) }
public static Boolean isCurrentMonth(TemporalAccessor temporal) {
Instant ref = Instant.now();
return Month.from(temporal) == Month.from(ref) && Year.from(temporal).equals(Year.from(ref));
}
}
Boolean result = givenDate.toInstant().query(TemporalQueries::isCurrentMonth); //Lambda using method reference
Time Zone
The other answers ignore the crucial issue of time zone. A new day dawns earlier in Paris than in Montréal. So at the same simultaneous moment, the dates are different, "tomorrow" in Paris while "yesterday" in Montréal.
Joda-Time
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them.
Instead use either Joda-Time library or the java.time package in Java 8 (inspired by Joda-Time).
Here is example code in Joda-Time 2.5.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( yourJUDate, zone ); // Convert java.util.Date to Joda-Time, and assign time zone to adjust.
DateTime now = DateTime.now( zone );
// Now see if the month and year match.
if ( ( dateTime.getMonthOfYear() == now.getMonthOfYear() ) && ( dateTime.getYear() == now.getYear() ) ) {
// You have a hit.
}
For a more general solution to see if a moment falls within any span of time (not just a month), search StackOverflow for "joda" and "interval" and "contain".
java.time (Java 8)
Java 8 provides the YearMonth class which represents a given month within a given year (e.g. January 2018). This can be used to compare against the YearMonth of the given date.
private boolean inCurrentMonth(Date givenDate) {
ZoneId timeZone = ZoneOffset.UTC; // Use whichever time zone makes sense for your use case
LocalDateTime givenLocalDateTime = LocalDateTime.ofInstant(givenDate.toInstant(), timeZone);
YearMonth currentMonth = YearMonth.now(timeZone);
return currentMonth.equals(YearMonth.from(givenLocalDateTime));
}
Note that this approach will work for any of the Java 8 time classes that have both a month and a date part (LocalDate, ZonedDateTime, etc.) and not just LocalDateTime.
As far as I know the Calendar class and all derived from it return the date using the get(). See the documentation for this class. Also here is an example taken from here:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);
System.out.println(sdf.format(calendar.getTime()));
System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);
System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);
which outputs
2013 Feb 28 13:24:56
year : 2013
month : 1
dayOfMonth : 28
dayOfWeek : 5
weekOfYear : 9
weekOfMonth : 5
hour : 1
hourOfDay : 13
minute : 24
second : 56
millisecond : 0
I think it was replaced because the new way offers a much simpler handling using a single function, which is much easier to remember.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse("2011-09-13");
Log.e(MY_DEBUG_TAG, "Output is "+ date.getYear() + " /" + date.getMonth() + " / "+ (date.getDay()+1));
Is out putting
09-13 14:20:18.740: ERROR/GoldFishActivity(357): Output is 111 /8 / 3
What is the issue?
The methods you are using in the Date class are deprecated.
You get 111 for the year, because getYear() returns a value that is the result of subtracting 1900 from the year i.e. 2011 - 1900 = 111.
You get 3 for the day, because getDay() returns the day of the week and 3 = Wednesday. getDate() returns the day of the month, but this too is deprecated.
You should use the Calendar class instead.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse("2011-09-13");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Log.e(MY_DEBUG_TAG, "Output is "+ cal.get(Calendar.YEAR)+ " /" + (cal.get(Calendar.MONTH)+1) + " / "+ cal.get(Calendar.DAY_OF_MONTH));
Read the javadoc of java.util.Date carefully.
getYear returns the number of years since 1900.
getMonth returns the month, starting from 0 (0 = January, 1 = February, etc.).
getDay returns the day of week (0 = Sunday, 1 = Monday, etc.), not the day of month.
And all these methods are deprecated. You shouldn't use them anymore.
how to get minimum and maximum date from given month in java using java.util.Calendar.
The minimum is always the 1st of this month. The maximum can be determined by adding 1 to month and subtracting 1 from the Calendar day field.
This could be done this way:
c = ... // get calendar for month you're interested in
int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH)
You could find minimum and maximum value the same way for any of components of the date.
Have you tried the following?
After setting your calendar object to your desired month,
calendar.getActualMaximum(Calendar.DATE);
For the minimum, I suppose it's always the first.
Hope that helps.
Minimum date is always 1
and Maximum date can be calculate as
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
int year = 2010;
int month = Calendar.FEBRUARY;
int date = 1;
int maxDay =0;
calendar.set(year, month, date);
System.out.println("First Day: " + formatter.format(calendar.getTime()));
//Getting Maximum day for Given Month
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(year, month, maxDay);
System.out.println("Last Day: " + formatter.format(calendar.getTime()));
Hopefully this will helps
I got solution as below,
public void ddl_month_valueChange(ValueChangeEvent event) {
int v_month = Integer.parseInt(event.getNewValue().toString()) - 1;
java.util.Calendar c1 = java.util.Calendar.getInstance();
c1.set(2011, v_month, 1);
Date d_set_att_from = c1.getTime();
cal_att_from_date.setValue(d_set_att_from);
c1.add(java.util.Calendar.MONTH, 1);
c1.add(java.util.Calendar.DATE, -1);
Date d_set_att_to = c1.getTime();
cal_att_to_date.setValue(d_set_att_to); }