码迷,mamicode.com
首页 > 编程语言 > 详细

java 时间转换帮助类

时间:2017-10-27 19:09:53      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:opened   null   bsp   ring   instance   settime   imp   rgs   imei   

技术分享
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by caohuiming on 2017/10/27.
 */
public class DateTimeUtil {
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    //region 对外提供方法区
    public static Date getDate(String dateString, String format) {
        String newFormat = format;
        if (format == null || "".equals(format.trim())) {
            newFormat = DATETIME_FORMAT;
        }

        SimpleDateFormat formatter = new SimpleDateFormat(newFormat);

        try {
            return formatter.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }


    public static String toStr(final long timeStamp, final String format){

        Calendar cal = calendar();
        cal.setTimeInMillis(timeStamp*1000);
        Date date=   cal.getTime();

        final SimpleDateFormat customFormat = new SimpleDateFormat();
        customFormat.applyPattern(format.trim());
        return customFormat.format(date);
    }
    //endregion 对外提供方法区

    //region 私有方法区
    /**
     * 当前时间
     * @return
     */
    private static Calendar calendar() {
        final Calendar cal = Calendar.getInstance(Locale.CHINESE);
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        return cal;
    }

    //endregion 私有方法区
}
时间转换帮助类
技术分享
 public static void main(String[] args) throws IOException {

        long dateTime_2047=2429913600L;//2047-01-01
        String dateTimeStr=DateTimeUtil.toStr(dateTime_2047,DateTimeUtil.DATE_FORMAT);
        System.out.println(dateTimeStr);//2047-01-01

        Date myDate= DateTimeUtil.getDate("2047-10-27 23:22:21",DateTimeUtil.DATETIME_FORMAT);
        long myDateLong=myDate.getTime()/1000;
        System.out.println(myDateLong);//2455802541
    }
测试方法

 

java 时间转换帮助类

标签:opened   null   bsp   ring   instance   settime   imp   rgs   imei   

原文地址:http://www.cnblogs.com/caohuimingfa/p/7744754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!