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.
Related
I want to retrieve same day previous year.
e.g. today is 2019-03-30 that is year 2019, week 26(week of year), day 7 (day of week).
I need to construct LocalDate which is year 2018, week 26(week of year), day 7 (day of week).
I could not find from java.time package which can built LocalDate like this.
It seems like you want the previous year date with same week of year and day of week as the given date. Below code with give you that result.
LocalDate currentLocalDate = LocalDate.now();
int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
LocalDate resultLocalDate = currentLocalDate
.minusYears(1)
.with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
.with(ChronoField.DAY_OF_WEEK, dayOfWeek);
Full Example (live copy):
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
class Example
{
private static void showDateInfo(LocalDate ld) {
int weekOfYear = ld.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
int dayOfWeek = ld.getDayOfWeek().getValue();
System.out.println(ld.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is week " + weekOfYear + ", day " + dayOfWeek);
}
public static void main (String[] args) throws java.lang.Exception
{
LocalDate currentLocalDate = LocalDate.of(2019, 6, 30);
showDateInfo(currentLocalDate);
int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
LocalDate resultLocalDate = currentLocalDate
.minusYears(1)
.with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
.with(ChronoField.DAY_OF_WEEK, dayOfWeek);
showDateInfo(resultLocalDate);
}
}
Output:
2019-06-30 is week 26, day 7
2018-07-01 is week 26, day 7
I believe that the other answers are close but not quite there yet. As far as I understand, you want to use the week scheme of the default locale, which the other answers don’t do. My suggestion is:
WeekFields wf = WeekFields.of(Locale.getDefault());
LocalDate today = LocalDate.now(ZoneId.of("Africa/Casablanca"));
int week = today.get(wf.weekOfYear());
int dow = today.get(wf.dayOfWeek());
System.out.println("Today is " + today + ", "
+ today.getDayOfWeek() + " of week " + week);
LocalDate correspondingDayLastYear = today.minusYears(1)
.with(wf.weekOfYear(), week)
.with(wf.dayOfWeek(), dow);
System.out.println("Last year was " + correspondingDayLastYear + ", "
+ correspondingDayLastYear.getDayOfWeek()
+ " of week " + correspondingDayLastYear.get(wf.weekOfYear()));
When running on my computer just now the output was:
Today is 2019-06-30, SUNDAY of week 26
Last year was 2018-07-01, SUNDAY of week 26
When I set my locale to US I get the same date, but a different week number since American weeks are defined differently:
Today is 2019-06-30, SUNDAY of week 27
Last year was 2018-07-01, SUNDAY of week 27
I believe that there will also be cases where different locales will give you different dates.
wf.dayOfWeek() gives you a field that numbers the days from 1 to 7 according to the first day of week in that particular locale. It’s important not just to use withDayOfWeek or equivalent, or you would risk sliding into a different week if not using ISO weeks.
Still my answer will not work always! If today is within week 53 of the year, it may very well be that last year didn’t have a week 53. Not much we can do about that. Another problem we can’t solve: In American weeks week 1 starts on January 1. If this is a Sunday, it is the first day for the week, but then week 1 of the previous year started on a Friday or Saturday, so week 1 didn’t have any Sunday.
If you're looking for an ISO week-year compatible function, this is working for me - so far =].
public class FiscalDateUtil {
private static Logger log = LoggerFactory.getLogger(FiscalDateUtil.class);
static public LocalDate previousYearComparisonDate(LocalDate date) {
final int weekYear = date.get(IsoFields.WEEK_BASED_YEAR);
final int weekLastYear = weekYear-1;
final DayOfWeek dayOfWeek = date.getDayOfWeek();
final int weekOfYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
final LocalDate adjustedLastYear = date
.with(IsoFields.WEEK_BASED_YEAR, weekLastYear)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekOfYear)
.with(TemporalAdjusters.nextOrSame(dayOfWeek));
if (log.isTraceEnabled()) {
log.trace("starting date {}", date.toString());
log.trace("starting date dow {}", date.getDayOfWeek());
log.trace("lastYear {}", weekLastYear);
log.trace("lastYear dow {}", dayOfWeek);
log.trace("adjustedLastYear {}", adjustedLastYear.toString());
log.trace("adjustedLastYear dow {}", adjustedLastYear.getDayOfWeek());
}
return adjustedLastYear;
}
}
You can add the number of days since beginning of year of the current date to the beginning of the year before.
This should do the trick:
String dateStr = "2019-03-30";
LocalDate date = LocalDate.parse(dateStr);
LocalDate newDate = LocalDate.parse(date.getYear() + "-01-01").plusDays(date.getDayOfYear());
System.out.println(newDate);
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;
}
I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);
I want to get the date of the first monday of the current week and the first friday of the current week.
I tried it this way:
Calendar calendarFirstDay = Calendar.getInstance(Locale.GERMANY);
Calendar calendarLastDay = Calendar.getInstance(Locale.GERMANY);
Date now = new Date();
calendarFirstDay.setTime(now);
calendarLastDay.setTime(now);
calendarFirstDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendarLastDay.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
MyTextView.setText(calendarFirstDay.get(Calendar.DATE) + "." + calendarFirstDay.get(Calendar.MONTH) + "." + calendarFirstDay.get(Calendar.YEAR) + " - " + calendarLastDay.get(Calendar.DATE) + "." + calendarLastDay.get(Calendar.MONTH) + "." + calendarLastDay.get(Calendar.YEAR));
If I try this script today (Sunday, 26.1.2014), the output is the following:
20.0.2014 - 24.0.2014
Correct would be 20.1.2014 - 24.1.2014
Does somebody knows why my month is zero?
From the JavaDocs:
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Thus the first month (January) has a MONTH value of 0, and not 1 (as you'd expect).
There's a much better solution though: use a DateFormat or SimpleDateFormat to format dates as text. That way, you simply don't have to worry about this and let the DateFormat take care of it. For example:
DateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
MyTextView.setText(
myFormat.format(calendarFirstDay.getTime()) + " - " +
myFormat.format(calendarLastDay.getTime())
);
As stated in
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#set(int,%20int,%20int)
if you use this method, January will be 0 and Decmember will be 11, so you should just add 1 to your month.
EDIT: You are using the get method but it's probably 0-based, too.
I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);