java-从date中获取年份

代码

package testJava;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class GetYearForDate {

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	System.out.println("由时间中获取年");
	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ENGLISH);// 设定格式
	String sToTimestamp = "2005-8-18 14:21:12.123";
	try {
	    java.util.Date timeDate = dateFormat.parse(sToTimestamp);
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTime(timeDate);	
	    int year = calendar.get(Calendar.YEAR);
	    System.out.println("year:"+year);
	} catch (Exception e) {
	    System.out.println(e.toString());
	}

    }

}

运行结果

由时间中获取年
year:2005

 

你可能感兴趣的:(java-编码笔记)