前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >常用的时间工具类

常用的时间工具类

作者头像
JaneYork
发布2023-10-11 14:01:10
1820
发布2023-10-11 14:01:10
举报
文章被收录于专栏:PUSDN平行宇宙软件开发者网

1.说明:收集一些常用的时间工具类,仅用作记录和学习交流。可以使用CTRL+F搜索关键字。

2.推荐一个时间格式在线转换工具,注意图中标记的转换单位

3.工具代码及注释。

代码语言:javascript
复制
	/**
	 * 将时间戳转为字符串
	 * @param timestamp 时间戳
	 * @return eg:2018-09-26 14:48:36
	 */
	public static String formatTimestamp(long timestamp) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(timestamp);
	}

	/**
	 * 将精确到秒的时间戳字符串,转为指定格式
	 * @param seconds
	 * @param format
	 * @return
	 */
	public static String timeStamp2DateString(String seconds, String format) {
		if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
			return "";
		}
		if (format == null || format.isEmpty())
			format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(Long.valueOf(seconds + "000")));
	}

	/**
	 * 
	 * @param timeStr
	 * @return 转换前 2016-09-11T06:31:15.207Z 转换后 2016-09-11 14:31:15.207
	 */
	public static String dateFormat(String timeStr) {
		try {
			timeStr = timeStr.replace("Z", " UTC");
			Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(timeStr);
			SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			String result = defaultFormat.format(date);
			return result;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取当前时间事件戳,精确到秒
	 * @param secFlag 是否精确到秒
	 */
	public static long getCurrentTimestamp(boolean secFlag) {
		if (secFlag) {
			return System.currentTimeMillis() / 1000;
		} else {
			return System.currentTimeMillis();
		}
	}

	/**
	 * 通过日期类获取当前时间戳,较慢,不推荐
	 */
	public static long getCurrentTimestamp3() {
		return Calendar.getInstance().getTimeInMillis();
	}
	/**
	 * 另一种方式,获取当前时间戳
	 * @return
	 */
	public static long getCurrentTimestamp2() {
		return new Date().getTime();
	}

	/**
	 * 得到当前时间的字符串表示。
	 * @return 字符串,如:2015-02-26
	 */
	public static String getNowDateString() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(new Date());
	}

    /**
     * 得到当前时间的字符串表示。
     * @return 字符串,如:2015-02-26 08:23:06
     */
    public static String getNowTimeString(){
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
    	return df.format(new Date());
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-10-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档