java 操作实例
Posted 雪夜杀机
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 操作实例相关的知识,希望对你有一定的参考价值。
1、日期的加减操作
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateCalculate { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 获取形如yyyy-MM-dd HH:mm:ss * @param date * @return */ public static String datetimeToString(Date date) { return sdf.format(date); } /** * 根据时间字符串获取日期 * @param dateString * @return * @throws ParseException */ public static Date stringToDatetime(String dateString) throws ParseException { return sdf.parse(dateString); } /** * 获取本月最后一天 * @return */ public static Date getMonthStartDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH,1); return calendar.getTime(); } /** * 获取本月最后一天 * @return */ public static Date getMonthEndDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); return calendar.getTime(); } /** * 获取指定日期所属周的开始时间 * @param date * @return */ public static Date getBeginWeekDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { dayOfWeek += 7; } cal.add(Calendar.DATE,2 - dayOfWeek); return cal.getTime(); } /** * 距离指定日期所属周结束时间 * @return */ public static Date getEndWeekDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { dayOfWeek += 7; } cal.add(Calendar.DATE,8 - dayOfWeek); return cal.getTime(); } /** * 对指定日期进行年份加减操作 * @param date * @param num * @return */ public static Date calculateDateOfYear(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR,num); return calendar.getTime(); } /** * 对指定日期月份进行加减操作 * @param date * @param num * @return */ public static Date calculateDateOfMonth(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH,num); return calendar.getTime(); } /** * 对指定日期天数进行加减操作 * @param date * @param num 负整数 正整数 * @return */ public static Date calculateDateOfDay(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH,num); return calendar.getTime(); } public static void main(String[] args) throws ParseException { System.out.println(datetimeToString(getMonthStartDate(sdf.parse("2019-12-04 12:09:52")))); System.out.println(datetimeToString(getEndWeekDate(sdf.parse("2019-12-04 12:09:52")))); System.out.println(datetimeToString(calculateDateOfYear(stringToDatetime("2019-12-04 12:09:52"),-2))); } }
以上是关于java 操作实例的主要内容,如果未能解决你的问题,请参考以下文章
spark关于join后有重复列的问题(org.apache.spark.sql.AnalysisException: Reference '*' is ambiguous)(代码片段