JAVA中String与Date类型互转

时间:2025-03-20 08:50:03

        String2Date              &&      Date2String

首先,感谢阅览,能够帮到你是我的荣幸,有不足的挺多指教。

在java中不支持String和Date直接转换,提供了一个转换中间类SimpleDateFormat(import ;),通过SimpleDateFormat提供的两个方法进行转换:

/**
     * Formats a Date into a date/time string.
     * @param date the time value to be formatted into a time string.
     * @return the formatted time string.
     */
    public final String format(Date date)
    {
        return format(date, new StringBuffer(),
                      ).toString();
    }

    /**
     * Parses text from the beginning of the given string to produce a date.
     * The method may not use the entire text of the given string.
     * <p>
     * See the {@link #parse(String, ParsePosition)} method for more information
     * on date parsing.
     *
     * @param source A <code>String</code> whose beginning should be parsed.
     * @return A <code>Date</code> parsed from the string.
     * @exception ParseException if the beginning of the specified string
     *            cannot be parsed.
     */
    public Date parse(String source) throws ParseException
    {
        ParsePosition pos = new ParsePosition(0);
        Date result = parse(source, pos);
        if ( == 0)
            throw new ParseException("Unparseable date: \"" + source + "\"" ,
                );
        return result;
    }

 创建SimpleDateFormat对象,相关函数语法

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
/**
    SimpleDateFormat函数语法:
  
         G 年代标志符
         y 年
         M 月
         d 日
         h 时 在上午或下午 (1~12)
         H 时 在一天中 (0~23)
         m 分
         s 秒
         S 毫秒
         E 星期
         D 一年中的第几天
         F 一月中第几个星期几
         w 一年中第几个星期
         W 一月中第几个星期
         a 上午 / 下午 标记符 
         k 时 在一天中 (1~24)
         K 时 在上午或下午 (0~11)
         z 时区 常见标准的写法"yyyy-MM-dd HH:mm:ss",注意大小写,时间是24小时制,24小时制转换成12小时制只需将HH改成hh,不需要另外的函数。
*/

 一般时间字符串格式:

/** 
   * 字符串转换为<br> 
   * 支持格式为 G 'at' hh:mm:ss z 如 '2022-1-1 AD at 22:10:59 PSD'<br> 
   * yy/MM/dd HH:mm:ss 如 '2022/1/1 17:55:00'<br> 
   * yy/MM/dd HH:mm:ss pm 如 '2022/1/1 17:55:00 pm'<br> 
   * yy-MM-dd HH:mm:ss 如 '2022-1-1 17:55:00' <br> 
   * yy-MM-dd HH:mm:ss am 如 '2022-1-1 17:55:00 am' <br> 
   */ 

 

项目中使用的相对校多,具体转换实例如下:



import .;

import ;
import ;
import .*;
import .*;

/**
 * @author: feng
 * @date: 2018/3/16
 * @description:
 */

public class DateUtils{

    private static final int DAY_MILLISECONDS = 1000 * 24 * 60 * 60;

    private static final int HOUR_MILLISECONDS = 1000 * 60 * 60;

    private static final int MINUTE_MILLISECONDS = 1000 * 60;

    //计算时间差,精确到天
    public static int diffDays(Date start, Date end) {
        long diff = () - ();
        return (int) (diff / (DAY_MILLISECONDS));
    }
    //计算时间差,精确到小时
    public static int diffHours(Date start, Date end) {
        long diff = () - ();
        return (int) (diff / (HOUR_MILLISECONDS));
    }
    //计算时间差,精确分钟
    public static int diffMinutes(Date start, Date end) {
        long diff = () - ();
        return (int) (diff / (MINUTE_MILLISECONDS));
    }
    //计算时间差,精确到分钟
    public static int diffSeconds(Date start, Date end) {
        long diff = () - ();
        return (int) (diff / 1000);
    }
    //获取当前时间,年-月-日
    public static Date getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = (new Date());
        Date date = null;
        try {
            date = (s);
        } catch (ParseException e) {

        }
        return date;
    }

    /**
     * 获取前几天的时间
     *
     * @param date currentDate
     * @param days beforeDate
     * @return
     */
    public static Date getDateBefore(Date date, int days) {
        Calendar now = ();
        (date);
        (, () - days);
        return ();
    }

    /**
     * 获取后几天的时间
     *
     * @param date currentDate
     * @param days afterDays
     * @return
     */
    public static Date getDateAfter(Date date, int days) {
        Calendar now = ();
        (date);
        (, () + days);
        return ();
    }
    //转换Date  to  String
    public static String date2String(Date date,String str){
        SimpleDateFormat sdf = new SimpleDateFormat(str);
        return (date);
    }

    public static Date parseDate(String str) {
        return parseDate(str, "yyyy-MM-dd");
    }
    //转换String  to  Date,入参str:转换字符串,例如2018-01-01 00:00:00  pattern:转换后格式
    public static Date parseDate(String str, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = (str);
        } catch (ParseException e) {
            ();
        }
        return date;
    }

    public static List<Date> getDatesBetween(Date startDate, Date endDate) {
        Long mils = (() - ()) / (DAY_MILLISECONDS);
        int days = ();
        List<Date> res = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            (.(startDate, i));
        }
        return res;
    }

    public static List<Date> getDatesBetweenIncludeEnd(Date startDate, Date endDate){
        List<Date> res = getDatesBetween(startDate, endDate);
        (endDate);
        return res;
    }

    public static Set<DayOfWeek> getWeekendDay(List<Integer> list) {
        Set<DayOfWeek> res = new HashSet<>();
        if ((list)) {
            return res;
        }
        for (Integer i : list) {
            switch (i) {
                case 1:
                    ();
                    break;
                case 2:
                    ();
                    break;
                case 3:
                    ();
                    break;
                case 4:
                    ();
                    break;
                case 5:
                    ();
                    break;
                case 6:
                    ();
                    break;
                case 7:
                    ();
                    break;
                default:
            }
        }
        return res;
    }

    public static DayOfWeek getDayOfWeek(Date date) {
        Instant instant = ();
        ZoneId zoneId = ();
        LocalDate localDate = (instant, zoneId).toLocalDate();
        return ();
    }

    /**
     * 将 1,2,3 .... 形式的星期集合  转化为 星期一,星期二,星期三 .... 这种形式
     *
     * @param weekDays
     * @return
     */
    public static List<String> weekDaysChange(List<String> weekDays) {
        List<String> newWeekDays = new ArrayList<>();
        for (String weekDay : weekDays) {
            switch (weekDay) {
                case "1":
                    ("星期一");
                    break;
                case "2":
                    ("星期二");
                    break;
                case "3":
                    ("星期三");
                    break;
                case "4":
                    ("星期四");
                    break;
                case "5":
                    ("星期五");
                    break;
                case "6":
                    ("星期六");
                    break;
                case "7":
                    ("星期日");
                    break;
                default:
            }
        }
        return newWeekDays;
    }

    public static DayOfWeek getDayOfWeekFromNumber(Integer day) {
        switch (day) {
            case 1:
                return ;
            case 2:
                return ;
            case 3:
                return ;
            case 4:
                return ;
            case 5:
                return ;
            case 6:
                return ;
            case 7:
                return ;
            default:
        }
        return ;
    }

    public static boolean isSameDay(Date date1, Date date2) {
        return .(date1, date2);
    }

    public static Date addDays(Date date, int days){
        return .(date, days);
    }

    public static int compareTime(Date date1, Date date2){
        int     t1;
        int     t2;
        t1 = (int) (() % (24*60*60*1000L));
        t2 = (int) (() % (24*60*60*1000L));
        return (t1 - t2);
    }

    public static boolean isValidTonight(Date date1, Date date2){
        Instant instant1 = ();
        ZoneId zone = ();
        LocalDateTime localDateTime1 = (instant1, zone);
        LocalTime localTime1 = ();

        Instant instant2 = ();
        LocalDateTime localDateTime2 = (instant2, zone);
        LocalTime localTime2 = ();

        LocalTime now = ();

        if((localTime2) && (localTime2)){
            return true;
        }else if((localTime2) && ((localTime1)||(localTime2))){
            return true;
        }
        return false;
    }
}