以 yyyy 为格式在 Java 中格式化年份
以 yyyy 格式化年份就像显示整个年份。例如,2018 年。
像这样使用 yyyy 格式 −
SimpleDateFormat("yyyy");
让我们看一个例子 −
// year in yyyy format SimpleDateFormat simpleformat = new SimpleDateFormat("yyyy"); String strYear = simpleformat.format(new Date()); System.out.println("Current Year = "+strYear);
上面我们使用了 SimpleDateFormat 类,因此导入了如下包 −
import java.text.SimpleDateFormat;
以下是示例 −
示例
import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss"); System.out.println("Date and time = "+simpleformat.format(cal.getTime())); // displaying date simpleformat = new SimpleDateFormat("dd/MMMM/yyyy"); String str = simpleformat.format(new Date()); System.out.println("Current Date = "+str); // year in yyyy format simpleformat = new SimpleDateFormat("yyyy"); String strYear = simpleformat.format(new Date()); System.out.println("Current Year = "+strYear); } }
输出
Date and time = Mon, 26 Nov 2018 11:12:39 Current Date = 26/November/2018 Current Year = 2018
广告