Date类型与String类型的相关问题

今天完成boss交代的任务时,遇到Date类型与String类型的相关问题,参考了网上的一些例子,并且自己写了demo,现在记录下了总结一下:

(一)判断一个字符串是不是合法的日期格式

public boolean StringisValidDate(String str) {
        boolean convertSuccess=true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess=false;
        }
        return convertSuccess;
    }

(二)将String转换为Date类

public Date stringToDate(String str) {
        // 科学计数法数据转为字符串
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(str);
        } catch (Exception e) {
        }
        return null;
    }

(三)将Date类型转换成String类型

 
public class DateToString1 {
	Date date = new Date();
	//DatetoString()
	date.toString();
 
}

猜你喜欢

转载自blog.csdn.net/JayInnn/article/details/81746327