When dealing with date data in Java, I was often confused, so I tried to organize it myself.
Date
Calendar
java.util.Date
java.util
is one of the packages that can handle Date typegetDay
: You can get the data of the day (0 = Sunday, 1 = Monday, ...)java.sql.Date
java.sql
is a packageDate→String
SimpleDateFormat
format (Date date)
methodDate date = new Date(); //Today's date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
System.out.println(date); // => Mon Dec 31 10:33:59 JST 2018
System.out.println(strDate); // => 2018-12-31
toString ()
method, it will be a string as it isDate date = new Date(); //Today's date
String strDate = date.toString();
System.out.println(date); // => Mon Dec 31 10:33:59 JST 2018
System.out.println(strDate); // => Mon Dec 31 10:33:59 JST 2018
String→Date
parse
methodParseException
in a class that uses the parse
methodpublic static void main(String[] args) throws ParseException{
String strDate = "2018-12-31";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(strDate);
System.out.println(date); // => Mon Dec 31 00:00:00 JST 2018
}
valueOf (String s)
methodjava.sql.Date
object
String strDate = "2018-12-31";
Date sqlDate = java.sql.Date.valueOf(strDate);
System.out.println(sqlDate); // => 2018-12-31
Date→Calendar
setTime (Date date)
methodDate date = new Date(); //Today's date
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar);
// =>java.util.GregorianCalendar[time=1546228443561,areFieldsSet=true, ...]
Calendar→Date
getTime ()
methodCalendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2018); //Set year
calendar.set(Calendar.MONTH, 11); //Set month(* MONTH starts from 0 0 → Jan, 1 → Feb,...become)
calendar.set(Calendar.DAY_OF_MONTH, 31);//Set date
Date date = calendar.getTime();
System.out.println(date); // => Mon Dec 31 13:01:05 JST 2018
I summarized how to handle date data that I have implemented. I would be grateful if you could give me some advice if you say "this is better" or "I often do this"! Wish you a good year!
Recommended Posts