java Date类与String类互相转换

在java程序中,获取当前时间

Date now = new Date(); //获取当前时间
Long longNow = now.getTime();//获取当前时间的时间戳
System.currentTimeMillis();// 获取当前毫秒值

把Date类的时间转为String字符串形式来表示—-format()方法

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

public String dateToStr(Date date){

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String stringNow = df.format(date);  //把当前时间转为字符串,字符串格式为yyyy-MM-dd  
    return stringNow ;
}

把String字符串表示的时间转为Date类—-parse()方法,会抛出异常

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

public Date strToDate(String time) throws ParseException{
    //String time = "2017-01-04 11:22:33";

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //1.设置字符串表示的时间的格式,格式要和time的格式保持一致
    Date date = null;
    if (!"".equals(time)) {
        date = df.parse(time);  //2.把字符串格式的时间转为Date类
    }

    return date ;
}


获取当前日期的年月日表示形式:Date转String再转Date

Date now = new Date(); // 当前日期
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 按日期查询,横坐标精确到秒
String nowString = df.format(now.getTime());
Date now2 = df.parse(nowString);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值