package cn.com.ultrapower.share;
import java.text.SimpleDateFormat;
import java.util.*;
public class FormatTime {
private static Date time;
private static SimpleDateFormat format;
private static String strtime;
/**
* 将字符串类型转换为长整型(按格式)
*
* @param strDate
* @param _format
* @return
*/
public static long formatToLongTime(String strDate, String _format) {
format = new SimpleDateFormat(_format, Locale.getDefault());
try {
time = format.parse(strDate);
return time.getTime() / 1000;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 将长整型的日期转化为指定日期格式
*
* @param intDate
* @return
*/
public static String longToFormatTime(long intDate, String _format) {
try {
if (intDate > 0) {
long c_unix_time2 = intDate;
time = new Date();
time.setTime(c_unix_time2 * 1000);
format = new SimpleDateFormat(_format, Locale.getDefault());
strtime = format.format(time);
} else {
strtime = "";
}
} catch (Exception ex) {
ex.printStackTrace();
}
return strtime;
}
/**
* 用于获得指定格式的当前日期
*
* @param _format
* 日期格式
*/
public static String getCurrentDate(String _format) {
String currentDate = "";
try {
Calendar calendar = GregorianCalendar.getInstance();
SimpleDateFormat simpleDateFormat;
Date date = calendar.getTime();
simpleDateFormat = new SimpleDateFormat(_format);
currentDate = simpleDateFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
currentDate = "";
}
return currentDate;
}
/**
* 获取时间差(可以通过此方法获取前N天的时间或前N个月的时间) 仔细摸索、其实这个方法挺实用的
* @param strDate
* 时间字符串
* @param intDate
* 时间差(秒)
* @param _format
* 时间格式(例:yyyy-MM-dd HH:mm:ss ,yyyyMMdd)
* @return
*/
public static String getCountTime(String strDate, long intDate,
String _format) {
try {
long _intDate = FormatTime.formatToLongTime(strDate, _format);
_intDate = intDate + _intDate;
strDate = FormatTime.longToFormatTime(_intDate, _format);
} catch (Exception ex) {
ex.printStackTrace();
}
return strDate;
}
/**
*
* @param strTime 时间字符串
* @param fmt1 旧时间格式
* @param fmt2 新时间格式
* ---yyyy-MM-dd HH:mm:ss
* @return
*/
public static String getTimeFMT_To_FMT(String strTime, String fmt1, String fmt2) {
String strDate = "";
try {
long intDate = FormatTime.formatToLongTime(strTime, fmt1);
strDate = FormatTime.longToFormatTime(intDate, fmt2);
} catch (Exception ex) {
ex.printStackTrace();
}
return strDate;
}
public static String formatIntToDateString01(long intDate,String fmt)
{
if(intDate>0)
{
long c_unix_time2 = intDate;
time = new Date();
time.setTime(c_unix_time2*1000);
format = new SimpleDateFormat(fmt, Locale.getDefault());
strtime = format.format(time);
}
else
{
strtime="";
}
return strtime;
}
public static void main(String[] args) {
String strTime = "2010-11-27 09:38:57";
System.out.println(FormatTime.getTimeFMT_To_FMT(strTime,"yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss"));
}
}
java几个时间转换的小方法,比较实用
最新推荐文章于 2024-08-03 17:44:51 发布