>  기사  >  Java  >  자바 날짜 변환

자바 날짜 변환

伊谢尔伦
伊谢尔伦원래의
2016-12-05 13:47:371530검색

포함된 핵심 클래스: Date 클래스, SimpleDateFormat 클래스, Calendar 클래스

1. 날짜 유형과 긴 유형

날짜 유형을 긴 유형으로 변환
날짜 날짜 = 새 날짜( ) ;//현재 시간 가져오기 날짜 유형

long date2long = date.getTime();//Date를 long으로

long 유형을 Date 유형으로
long cur = System.currentTimeMills( );//현재의 긴 시간 유형을 가져와서 반환

Date long2date = new Date(cur);//long을 날짜로 변환

2. 날짜 유형 및 문자열 유형

날짜 유형을 문자열 유형으로 변환
Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");//Set 대상 변환 형식은 yyyy-MM-dd HH:mm:ss.SSS

String date2string = sdf.format(date);//Date to String

String 유형을 Date 유형으로
String str="2001-11-03 11:12:33.828";//초기 문자열 유형 날짜 설정

날짜 str2date=sdf.parse(str);//문자열을 날짜로 변환

3. 날짜 유형 및 달력 유형

날짜 유형이 달력 유형으로 변환됨
Calendar cal = Calendar.getInstance();//현재 시간 가져오기 달력 유형

cal.setTime(date) ; //날짜를 달력으로

달력 유형을 날짜 유형으로 변환
Calendar cal = Calendar.getInstance();//현재 시간 달력 유형 가져오기

Date cal2date = cal.getTime( );//Calendar to Date

4. 요약

String과 기본 유형 간의 변환은 String.valueOf() 메소드에 의존합니다. 날짜 및 문자열 클래스 SimpleDateFormat 클래스를 사용합니다.
날짜 및 긴 변환은 Date에서 제공하는 구성 및 getTime() 메서드를 사용합니다.
날짜 및 달력 변환은 Calendar에서 제공하는 setTime() 및 getTime() 메서드를 사용합니다. 🎜> 5. 면접 질문

Q: 메소드를 작성하고, 매개변수는 Date 날짜이고, 날짜를 3일 뒤로 밀고, "yyyy-mm-dd" 형식으로 문자열 유형을 반환합니다.

public String add3Day(Date date) throws ParseException{
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);//Date转换为Calendar
   cal.add(Calendar.DATE, 3);//将日期往后推3天,减少3天则-3. 月增加则Calendar.MONTH
   String after = sdf.format(cal.getTime());//Calendar转换为Date,再转换为String
   return after;
}

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.