- package com.playtogether.utils;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- public class DateUtils {
- /**
- * unix时间戳转换为dateFormat
- *
- * @param beginDate
- * @return
- */
- public static String timestampToDate(String beginDate) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String sd = sdf.format(new Date(Long.parseLong(beginDate)));
- return sd;
- }
- /**
- * 自定义格式时间戳转换(网站优化)
- *
- * @param beginDate
- * @return
- */
- public static String timestampToDate(String beginDate,String format) {
- SimpleDateFormat sdf = new SimpleDateFormat(format);
- String sd = sdf.format(new Date(Long.parseLong(beginDate)));
- return sd;
- }
- /**
- * 将字符串转为时间戳
- *
- * @param user_time
- * @return
- */
- public static String dateToTimestamp(String user_time) {
- String re_time = null;
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
- Date d;
- try {
- d = sdf.parse(user_time);
- long l = d.getTime();
- String str = String.valueOf(l);
- re_time = str.substring(0, 10);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return re_time;
- }
- }
- java 时间戳与Date 相互转化相关函数
2010-05-06 13:14
一.日期转换为时间戳
public long getTimestamp() throws ParseException{
Date date1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
.parse("2009/12/11 00:00:00");
Date date2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
.parse("1970/01/01 08:00:00");
long l = date1.getTime() - date2.getTime() > 0 ? date1.getTime()
- date2.getTime() : date2.getTime() - date1.getTime();
long rand = (int)(Math.random()*1000);
return rand;
}
二.时间戳转换为date 型
public void getDate(String unixDate) {
SimpleDateFormat fm1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
SimpleDateFormat fm2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
long unixLong = 0;
String date = "";
try {
unixLong = Long.parseLong(unixDate) * 1000;
} catch(Exception ex) {
System.out.println("String转换Long错误,请确认数据可以转换!");
}
try {
date = fm1.format(unixLong);
date = fm2.format(new Date(date));
} catch(Exception ex) {
System.out.println("String转换Date错误,请确认数据可以转换!");
}
System.out.println(date);
}
浅析Date与Java 时间戳相互转换
最新推荐文章于 2024-07-13 02:39:28 发布