在软件开发中,我们会经常遇到各种时间的显示及判断,这就需要我们对获取的数据进行转换。
“yyyy-MM-dd HH:mm:ss” 这是常用的时间显示格式,表示了“年-月-日 时:分:秒”
1、日期字符串转换Date实体
public static Date parseServerTime(String serverTime, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd HH:mm:ss"; } SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE); sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); Date date = null; try { date = sdf.parse(serverTime); } catch (Exception e) { Timber.e(e, ""); } return date; }参数一:时间字符串; 参数二:日期格式
2、秒数转换成时分秒
public static String convertSecToTimeString(long lSeconds) { long nHour = lSeconds / 3600; long nMin = lSeconds % 3600; long nSec = nMin % 60; nMin = nMin / 60; return String.format("%02d小时%02d分钟%02d秒", nHour, nMin, nSec); }
3、Date对象获取时间字符串
public static String getDateStr(Date date,String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd HH:mm:ss"; } SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(date); }
4、时间戳转换日期格式字符串
public static String timeStamp2Date(long time, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd HH:mm:ss"; } SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(new Date(time)); }
5、日期格式字符串转换时间戳
public static String date2TimeStamp(String date, String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); return String.valueOf(sdf.parse(date).getTime() / 1000); } catch (Exception e) { e.printStackTrace(); } return ""; }
6、
/** * 获取某个日期前后N天的日期 * * @param beginDate * @param distanceDay 前后几天 如获取前7天日期则传-7即可;如果后7天则传7 * @param format 日期格式,默认"yyyy-MM-dd" * @return */ public static String getOldDateByDay(Date beginDate, int distanceDay, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd"; } SimpleDateFormat dft = new SimpleDateFormat(format); Calendar date = Calendar.getInstance(); date.setTime(beginDate); date.set(Calendar.DATE, date.get(Calendar.DATE) + distanceDay); Date endDate = null; try { endDate = dft.parse(dft.format(date.getTime())); } catch (Exception e) { e.printStackTrace(); } return dft.format(endDate); }
7、
/** * 获取前后几个月的日期 * @param beginDate * @param distanceMonth * @param format * @return */ public static String getOldDateByMonth(Date beginDate, int distanceMonth, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd"; } SimpleDateFormat dft = new SimpleDateFormat(format); Calendar date = Calendar.getInstance(); date.setTime(beginDate); date.set(Calendar.MONTH, date.get(Calendar.MONTH) + distanceMonth); Date endDate = null; try { endDate = dft.parse(dft.format(date.getTime())); } catch (Exception e) { e.printStackTrace(); } return dft.format(endDate); }