java时间Long和String相互转化

package com.banksteel.openerp.commons.utils;

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

/**
 * @description:时间转换
 * @projectName:openerp-commons
 * @className:TimeTransf.java
 * @author:
 * @createTime:2016年7月28日 下午6:06:53
 * @version 1.0
 */
public class TimeTransf
{
	/**
	 * @description:字符串型时间转换成长整型时间
	 * @param time 字符串型时间
	 * @param format 时间表现形式
	 * @return 长整型时间
	 * @throws ParseException
	 * @author:
	 * @createTime:2016年7月28日 下午6:07:33
	 */
	public static Long StringToLong(String time, String format) throws ParseException
	{
		if(time!=null){
			return new SimpleDateFormat(format).parse(time).getTime();
		}
		return null;
	}

	/**
	 * @description:长整型时间转换成字符串型时间
	 * @param time 长整型时间
	 * @param format 时间表现形式
	 * @return 字符串型时间
	 * @author:
	 * @createTime:2016年7月28日 下午6:10:50
	 */
	public static String LongToString(Long time, String format)
	{
		if(time!=null){
			return new SimpleDateFormat(format).format(new Date(time));
		}
		return null;
	}

	public static void main(String[] args) throws ParseException
	{
		Long currentTimeMillis = System.currentTimeMillis();
		String str = TimeTransf.LongToString(currentTimeMillis, "yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println(str);
		Long t = TimeTransf.StringToLong(str, "yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println(t);

		String str1 = TimeTransf.LongToString(currentTimeMillis, "yyyy-MM-dd HH:mm:ss");
		System.out.println(str1);
		Long t1 = TimeTransf.StringToLong(str1, "yyyy-MM-dd HH:mm:ss");
		System.out.println(t1);

		String str2 = TimeTransf.LongToString(currentTimeMillis, "yyyy-MM-dd");
		System.out.println(str2);
		Long t2 = TimeTransf.StringToLong(str2, "yyyy-MM-dd");
		System.out.println(t2);
	}
}

  2

猜你喜欢

转载自www.cnblogs.com/guilf/p/9298254.html
今日推荐