Java method to get the time year month and day
- 2020-04-01 03:52:58
- OfStack
This article illustrates how Java gets the year, month, and day. Share with you for your reference. The specific implementation method is as follows:
package com.date.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
System.out.println("--------------- Gets the date of the current time -----------------");
getMonthDay();
System.out.println("--------------- Gets the year, month and day of the custom time -----------------");
getMonthDay2Set();
}
private static void getMonthDay2Set() {
String dateStr = "2013-11-10 18:45:39";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
Date dt = null;
try {
dt = sdf.parse(dateStr);
cal.setTime(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.println("=== years ===" + year);
System.out.println("=== month ===" + month);
System.out.println("=== day ===" + day);
System.out.println("=== when ===" + hour);
System.out.println("=== points ===" + minute);
System.out.println("=== seconds ===" + second);
}
private static void getMonthDay() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.println("=== years ===" + year);
System.out.println("=== month ===" + month);
System.out.println("=== day ===" + day);
System.out.println("=== when ===" + hour);
System.out.println("=== points ===" + minute);
System.out.println("=== seconds ===" + second);
}
}
I hope this article has been helpful to your Java programming.