java 获取当前的日期、时间, 日期、字符串、long之间的相互转换

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


/** DateTime.java: 用于实现,日期、字符串、long之间的相互转换。----- 2016-05-05 下午4:59:16 wangzhongyuan */
public class DateTime
{
	/** main */
	public static void main(String[] args)
	{
		String currentTime = currentTime();					// 获取当前时间的字符串形式
		long currentLong = currentTimeLong();				// 获取当前时间的long型
		
		System.out.println("示例输出:");
		
		System.out.println("currentTime: " + currentTime);
		System.out.println("currentLong: " + currentLong);
		
		Date stringToDate = toDate(currentTime);			// 日期字符串转化为日期
		Date longToDate = toDate(currentLong);				// long转化为日期
		
		System.out.println("stringToDate: " + toString(stringToDate));	// 显示为日期串
		System.out.println("longToDate: " + toString(longToDate));		// 显示为日期串
	}
	
	// 获取当前时间,long型
	public static long currentTimeLong()
	{
		return new Date().getTime();
	}
	
	// 获取当前时间,字符串形式
	public static String currentTime()
	{
		Date date = new Date();
		return toString(date);
	}
	
	// 从字符串, 获取日期, 如time = "2016-3-16 4:12:16"
	public static Date toDate(String time)
	{
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf.parse(time);
			
			return date;
		}
		catch (ParseException e)
		{
			return null;
		}
	}
	
	// 从long, 获取日期
	@SuppressWarnings("unused")
	public static Date toDate(long millSec)
	{
		return new Date(millSec);
	}
	
	// 日期转化为字符串形式
	public static String toString(Date date)
	{
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}
}

/**
 * 获取当前的系统时间,以秒为单位, java.util.Date.Date()
 */
private static long currentTime()
{
	return new Date().getTime()/1000;	//获取当前时间的秒数值	
}


/**
 * 获取当前日期
 */
@SuppressLint("SimpleDateFormat")
private static String currentDate()
{
	SimpleDateFormat F = new SimpleDateFormat("yyyy/MM/dd");
	return F.format(new Date());
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值