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)); } }
運行結果:php
2019
-
03
-
26
2019
-
03
-
26
09
:
59
:
06
2019
年
03
月
26
日
09
:
59
:
06
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); } }
運行結果:java
Tue Mar 26 09:20:02 CST 2019c++
java的date默認精度是毫秒,也就是說生成的時間戳就是13位的,而像c++或者php生成的時間戳默認就是10位的,由於其精度是秒。spa
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); }
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; }
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; }