The below code is to check the day of the week, now I want to check the date, month, year ...how to modify it?
import java.util.Calendar
ImageView imageView;
Calendar cal = Calendar.getInstance();
cal.setTime(now_date);
imageView = (ImageView)findViewById(R.id.imageView);
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
imageView.setImageResource(R.drawable.IMAGE1);
} else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
imageView.setImageResource(R.drawable.IMAGE2);
}
CodePudding user response:
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API: Use ZonedDateTime
with the applicable ZoneId
and retrieve the required values from it.
Demo:
import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Specify the applicable ZoneId e.g.
// ZonedDateTime.now(ZoneId.of("Asia/Kolkata"))
// to get the current date-time in that timezone
ZonedDateTime now = ZonedDateTime.now();
DayOfWeek dow = now.getDayOfWeek();
System.out.println(dow);
int weekDayNum = dow.getValue();
System.out.println(weekDayNum);
String weekDayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(weekDayName);
int year = now.getYear();
System.out.println(year);
Month month = now.getMonth();
System.out.println(month);
int monthValue = month.getValue();
System.out.println(monthValue);
int dayOfMonth = now.getDayOfMonth();
System.out.println(dayOfMonth);
int dayOfYear = now.getDayOfYear();
System.out.println(dayOfYear);
}
}
Output:
MONDAY
1
Monday
2021
NOVEMBER
11
1
305
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time
API with JDBC.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.
CodePudding user response:
Similar to DAY_OF_WEEK, you can get other fields from Calendar instance.
Please check Java Docs for more details: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
CodePudding user response:
Refer to the documentation https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html you can get the week, month and year in this way
Date today = new Date();
cal.setTime(today);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);