常用的java时间格式转化,比较基础啊,看代码,有注释
package com.DateConvert;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConvert
{
/**
* 获取当前时间转化为yyyy-MM-dd HH:mm:ss格式
* @version
* @describe
* @return dateString
*/
public static String getNowDate()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 得到现在小时
* @version
* @describe 转化为yyyy-MM-dd HH:mm:ss格式,再通过截取方式获得时间或者分钟,秒
* @return String
*/
public static String getHour()
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString.substring(11, 13);
}
/**
* 时间戳转化
* @version
* @describe
* @param unixDate 格式为:十位时间戳或者十三位时间戳,位数不够用0补齐
* @return
*/
public static String getDate(String unixDate)
{
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
long unixLong = 0;
String date = "";
try
{
if (unixDate.length() > 10)
{
unixLong = Long.parseLong(unixDate);
}
else
{
// 时间戳为十位时,调用,时间戳改为十三位
unixLong = Long.parseLong(unixDate) * 1000;
}
date = simple.format(unixLong);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return date;
}
/**
* date 转化为时间戳
* @version
* @describe 返回值为十三位时间戳
* @param date 格式为:yyyy-MM-dd hh:mm:ss 或者为:yyyy-MM-dd hh:mm:ss.0
* @return
* @throws ParseException
*/
public static long getTimestamp(String date)
{
Date date1;
Date date2;
long l = 0;
try
{
date1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(date);
date2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("1970/01/01 08:00:00");
l = date1.getTime() - date2.getTime() > 0 ? date1.getTime() - date2.getTime() : date2.getTime()
- date1.getTime();
}
catch (ParseException e)
{
e.printStackTrace();
}
return l;
}
/**
* 时间前推或后推分钟,其中mm表示分钟.
* @version
* @describe 换算成时间戳,再转化为yyyy-MM-dd HH:mm:ss格式
* @param sj 时间
* @param mm 推迟时间
* @return
*/
public static String getPreTime(String sj, String mm)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDate = "";
try
{
Date date1 = format.parse(sj);
long Time = (date1.getTime() / 1000) + Integer.parseInt(mm) * 60;
date1.setTime(Time * 1000);
myDate = format.format(date1);
}
catch (Exception e)
{
e.printStackTrace();
}
return myDate;
}
}