1、日期转String(格式化)

package com.test.dateFormat;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.junit.Test;
 
public class Date2String {
    @Test
    public void test() {
        //获取当前日期
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(date));
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(date));
        sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println(sdf.format(date));
    }
}

运行结果:

2019-03-26
2019-03-26 09:59:06
20190326日 09:59:06
 

2、String转日期(解析)

package com.test.dateFormat;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.junit.Test;
import java.util.Date;
 
public class String2Date {
    @Test
    public void test() throws ParseException {
        String string = "2019-03-26 09:20:02";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     Date date=sdf.parse(string);
        System.out.println(date); 
   } 
}

运行结果:

Tue Mar 26 09:20:02 CST 2019

3、String 转时间戳

java的date默认精度是毫秒,也就是说生成的时间戳就是13位的,而像c++或者php生成的时间戳默认就是10位的,因为其精度是秒。

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

public void testString2Date() {
        String startDate = "2017-08-15";
        String endDate = "2017-08-15";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        int startDay = 0;
        int endDay = 0;

        try {
            Date dateStart = format.parse(startDate);
            Date datEnd = format.parse(endDate);

            startDay = (int) (dateStart.getTime() / 1000);
            endDay = (int) (datEnd.getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println(startDay);
        System.err.println(endDay);
    }

4、时间戳(13位)转化为时间

 public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

5、给定时间增加3个月

public static String addmonth(String date,int month){
   SimpleDateFormat dsdf=new    SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   SimpleDateFormat dsdf=new    SimpleDateFormat("yyyy-MM-dd");
   Date sourceDate;
   String time=null;
   try{
        sourceDate=dsdf.parse(date);
        Calendar c=Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH,month);
        time=dsd.format(c.getTime());
   }catch{
      e.printStackTrace();
   }
   return time;

}

 

 

posted on 2019-03-26 10:38  丁昆  阅读(121)  评论(0编辑  收藏  举报