SimpleDateFormat与DateTimeFormatter的常规操作

话不多说,直接上代码,看懂基本就会用了系列

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateTimeUtil {
     
	/*
	 * SimpleDateFormat
	 */
	private static void SimpleDate() {
     
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		Date date = new Date();
		System.out.println(date);
		String str = sdf.format(date);		//Date-String
		System.out.println(str);
		try {
     
			Date date2 = sdf.parse(str);	//String-Date
			System.out.println(date2);
		} catch (ParseException e) {
     
			e.printStackTrace();
		}
	}
	
	/*
	 * DateTimeFormatter
	 */    
    //str->Date
    public static Date strToDate(String dateTimeStr,String formatStr){
     
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }
    //Date->str
    public static String dateToStr(Date date,String formatStr){
     
        if(date == null){
     
            return null;	//commons-lang3-x.x.x.jar包:return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(formatStr);
    }

/*
	public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";		//常用时间格式
    //str->Date - 采用常用时间格式
    public static Date strToDate(String dateTimeStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }
    //Date->str - 采用常用时间格式
    public static String dateToStr(Date date){
        if(date == null){
            return null;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(STANDARD_FORMAT);
    }
*/    
    
	public static void main(String[] args) {
     
		//SimpleDateFormat-非线程安全
		System.out.println("======SimpleDateFormat-非线程安全======");
		SimpleDate();
		
		//DateTimeFormatter-线程安全-导jar包:joda-time-x.x.x.jar
		System.out.println("======DateTimeFormatter-线程安全======");
		System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        System.out.println(DateTimeUtil.strToDate("2020-08-25 13:14:52","yyyy-MM-dd HH:mm:ss"));
	}
	
}

DateTimeFormatter-线程安全-导jar包:joda-time-x.x.x.jar:https://mvnrepository.com/artifact/joda-time/joda-time

一个较好但“不完整”的介绍:https://www.jianshu.com/p/b212afa16f1f

你可能感兴趣的:(Java,java,多线程)