时间与时间戳的转化/时间与时间字符串的转化/字符串与时间戳的转化

package cn.meiriting.common.utils;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


import org.apache.commons.lang3.StringUtils;  
  
  
/** 
 * @author DingJiaCheng 
 * */  
public class DateFormatUtil {  
      
    /** 
     * 时间戳转日期 
     * @param ms 
     * @return 
     */  
    public static Date transForDate(Integer ms){  
        if(ms==null){  
            ms=0;  
        }  
        long msl=(long)ms*1000;  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date temp=null;  
        if(ms!=null){  
            try {  
                String str=sdf.format(msl);  
                temp=sdf.parse(str);  
            } catch (ParseException e) {  
                e.printStackTrace();  
            }  
        }  
        return temp;  
    }  
      
    /** 
     * 获取晚上9点半的时间戳 
     *  
     * @return 
     */  
    public static int getTimes(int day, int hour, int minute) {  
        Calendar cal = Calendar.getInstance();  
        cal.add(Calendar.DATE, day);  
        cal.set(Calendar.HOUR_OF_DAY, hour);  
        cal.set(Calendar.SECOND, 0);  
        cal.set(Calendar.MINUTE, minute);  
        cal.set(Calendar.MILLISECOND, 0);  
        return (int) (cal.getTimeInMillis() / 1000);  
    }  
      
    /** 
     * 获取当前时间往上的整点时间 
     *  
     * @return 
     */  
    public static int getIntegralTime() {  
        Calendar cal = Calendar.getInstance();  
        cal.add(Calendar.HOUR_OF_DAY, 1);  
        cal.set(Calendar.SECOND, 0);  
        cal.set(Calendar.MINUTE, 0);  
        cal.set(Calendar.MILLISECOND, 0);  
        return (int) (cal.getTimeInMillis() / 1000);  
    }  
      
    public static int getIntegralTimeEnd() {  
        Calendar cal = Calendar.getInstance();  
        cal.set(Calendar.HOUR_OF_DAY, 24);  
        cal.set(Calendar.SECOND, 0);  
        cal.set(Calendar.MINUTE, 0);  
        cal.set(Calendar.MILLISECOND, 0);  
        return (int) (cal.getTimeInMillis() / 1000);  
    }  
      
      
      
  
      
      
    /** 
     * 时间戳转日期 
     * @param ms 
     * @return 
     */  
    public static Date transForDate3(Integer ms){  
        if(ms==null){  
            ms=0;  
        }  
        long msl=(long)ms*1000;  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");  
        Date temp=null;  
        if(ms!=null){  
            try {  
                String str=sdf.format(msl);  
                temp=sdf.parse(str);  
            } catch (ParseException e) {  
                e.printStackTrace();  
            }  
        }  
        return temp;  
    }  
    /** 
     * 时间戳转日期 
     * @param ms 
     * @return 
     */  
    public static Date transForDate(Long ms){  
        if(ms==null){  
            ms=(long)0;  
        }  
        long msl=(long)ms*1000;  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date temp=null;  
        if(ms!=null){  
            try {  
                String str=sdf.format(msl);  
                temp=sdf.parse(str);  
            } catch (ParseException e) {  
                e.printStackTrace();  
            }  
        }  
        return temp;  
    }  
      
      
    public static String transForDate1(Integer ms){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
              
            if(ms!=null){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }         
        return str;  
    }  
    public static String transForDate2(Integer ms){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
              
            if(ms!=null){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }         
        return str;  
    }  
      
    public static String transForDate4(Integer ms){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd");  
              
            if(ms!=null){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }         
        return str;  
    }  
      
      
    public static String transForDate5(Integer ms){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
              
            if(ms!=null){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }         
        return str;  
    }  
      
    public static String transForDateInChinese(Integer ms){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");  
              
            if(ms!=null){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }         
        return str;  
    }  
      
    /** 
     * 日期转时间戳 
     * @param date 
     * @return 
     */  
    public static Integer transForMilliSecond(Date date){  
        if(date==null) return null;  
        return (int)(date.getTime()/1000);  
    }  
      
    /** 
     * 获取当前时间戳 
     * @return 
     */  
    public static Integer currentTimeStamp(){  
        return (int)(System.currentTimeMillis()/1000);  
    }  
      
    /** 
     * 日期字符串转时间戳 
     * @param dateStr 
     * @return 
     */  
    public static Integer transForMilliSecond(String dateStr){  
        Date date = DateFormatUtil.formatDate(dateStr);  
        return date == null ? null : DateFormatUtil.transForMilliSecond(date);  
    }  
    /** 
     * 日期字符串转时间戳 
     * @param dateStr 
     * @return 
     */  
    public static Integer transForMilliSecond(String dateStr,String format){  
        Date date = DateFormatUtil.formatDate(dateStr,format);  
        return date == null ? null : DateFormatUtil.transForMilliSecond(date);  
    }  
    /** 
     * 日期字符串转时间戳 
     * @param dateStr 
     * @param 格式 如"yyyy-mm-dd" 
     * @return 
     */  
    public static Integer transForMilliSecondByTim(String dateStr,String tim){  
        SimpleDateFormat sdf=new SimpleDateFormat(tim);  
        Date date =null;  
        try {  
            date = sdf.parse(dateStr);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return date == null ? null : DateFormatUtil.transForMilliSecond(date);  
    }  
    /** 
     * 字符串转日期,格式为:"yyyy-MM-dd HH:mm:ss" 
     * @param dateStr 
     * @return 
     */  
    public static Date formatDate(String dateStr){  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date result=null;  
        try {  
            result = sdf.parse(dateStr);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
    /** 
     * 字符串转日期,格式为:"yyyy-MM-dd HH:mm:ss" 
     * @param dateStr 
     * @return 
     */  
    public static Date formatDate(String dateStr,String format){  
        SimpleDateFormat sdf=new SimpleDateFormat(format);  
        Date result=null;  
        try {  
            result = sdf.parse(dateStr);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
    /** 
     * 日期转字符串 
     * @param date 
     * @return 
     */  
    public static String formatDate(Date date){  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String result=null;  
        result = sdf.format(date);  
        return result;  
    }  
    /** 
     * 日期转字符串 
     * @param date 
     * @return 
     */  
    public static String formatDate(Date date,String format){  
        SimpleDateFormat sdf=new SimpleDateFormat(format);  
        String result=null;  
        result = sdf.format(date);  
        return result;  
    }  
    /** 
     * 时间戳格式化输出(httl模版用) 
     *  
     * @param ms        时间戳 
     * @param format    格式化 
     * @return 
     */  
    public static String transForDate(Integer ms, String format){  
        String str = "";  
        if(ms!=null){  
            long msl=(long)ms*1000;  
            SimpleDateFormat sdf=new SimpleDateFormat(format);  
            if(!ms.equals(0)){  
                try {  
                    str=sdf.format(msl);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return str;  
    }     
      
    /** 
     * 取BigDecimal类型数的整数或小数部分(httl模版用) 
     *  
     * @param b 值 
     * @param mode  模式 0取整 1去小数部分 
     * @return 
     */  
    public static String splitBigDecimal(BigDecimal b, int mode) {  
        DecimalFormat df = new DecimalFormat("0.00");  
        String s = df.format(b);  
        if(mode==0){  
            return s.split("\\.")[0];  
        }else {  
            return "."+s.split("\\.")[1];  
        }  
    }  
      
    /** 
     * 计算两个日期之间差的天数(httl模版用) 
     *  
     * @param ts1   时间戳1 
     * @param ts2   时间戳2 
     * @return 
     */  
    public static int caculate2Days(Integer ts1, Integer ts2) {  
        Date firstDate = DateFormatUtil.transForDate(ts1);  
        Date secondDate = DateFormatUtil.transForDate(ts2);  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(firstDate);  
        int dayNum1 = calendar.get(Calendar.DAY_OF_YEAR);  
        calendar.setTime(secondDate);  
        int dayNum2 = calendar.get(Calendar.DAY_OF_YEAR);  
        return Math.abs(dayNum1 - dayNum2);  
    }  
      
    /** 
     * 给手机加密中间四位加星号 
     *  
     * @param mobile 
     * @return 
     */  
    public String mobileSerect(String mobile){  
        if(!StringUtils.isBlank(mobile)){  
            int between = mobile.length()/2;  
            mobile = mobile.substring(0, between-2)+"****"+mobile.substring(between+2, mobile.length());  
        }  
        return mobile;  
    }  
      
    /** 
     * 给邮箱加密加星号 
     *  
     * @param email 
     * @return 
     */  
    public String emailSerect(String email) {  
        if(!StringUtils.isBlank(email)){  
            int length = email.lastIndexOf("@");  
            email = email.substring(0, 2)+"****"+email.substring(length-2, email.length());  
        }  
        return email;  
    }  
      
    /** 
     * BigDecimal类型数据相加 
     *  
     * @param BigDecimal source 
     * @param BigDecimal target 
     * @return 
     */  
    public BigDecimal sumBigDicimal(BigDecimal source, BigDecimal target) {  
        source = source.add(target);  
        return source;  
    }  
      
    /** 
     * BigDecimal类型数据相加 
     *  
     * @param BigDecimal source 
     * @param BigDecimal target 
     * @return 
     */  
    public BigDecimal sumBigDicimalAndDouble(BigDecimal source, Double target) {  
        BigDecimal new_target = new BigDecimal(target);  
        source = source.add(new_target);  
        return source;  
    }  
      
    /** 
     * BigDecimal类型数据相减 
     *  
     * @param BigDecimal source 
     * @param BigDecimal target 
     * @return 
     */  
    public BigDecimal subBigDicimal(BigDecimal source, BigDecimal target) {  
        source = source.subtract(target);  
        return source;  
    }  
      
    /** 
     * 获取传入时间和当前时间的时间差 
     * @return 
     */  
    public static Long getTimediff(int timeStamp){  
        Date d1 = DateFormatUtil.transForDate(timeStamp);  
        Date today = new Date();  
        if(d1.getTime()<today.getTime()){  
            return null;  
        }  
        return (d1.getTime()-today.getTime())/1000;  
    }  
  
    /** 
     * 获取某周的第一天日期 
     * @param week 0 当周 1 上一周 -1 下一周 
     * @return 
     */  
    public static String weekFirstDay(int week){  
        Calendar c1 = Calendar.getInstance();  
        int dow = c1.get(Calendar.DAY_OF_WEEK);  
        c1.add(Calendar.DATE, -dow-7*(week-1)-5 );  
        String d1 = new SimpleDateFormat("yyyy-MM-dd").format(c1.getTime());  
        return d1+" 00:00:00";  
    }  
      
    /** 
     * 当前时间加一年 
     */  
    public static String addYear(int startTime){  
        Date firstDate = DateFormatUtil.transForDate(startTime);  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(firstDate);  
        calendar.add(Calendar.YEAR,1);  
        String d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());  
        return d1;  
    }  
      
    /** 
     * 获取某周的最后一天日期 
     * @param week 
     * @return 
     */  
    public static String weekLastDay(int week){  
        Calendar c1 = Calendar.getInstance();  
        int dow = c1.get(Calendar.DAY_OF_WEEK);  
        c1.add(Calendar.DATE, -dow-7*(week-1)+1);  
        String d1 = new SimpleDateFormat("yyyy-MM-dd").format(c1.getTime());  
        return d1+" 23:59:59";  
    }     
      
    /** 
     * 和当前时间比对 
     * @return 
     */  
    public static boolean greaterThanNow(int timeStamp){  
        Date d1 = DateFormatUtil.transForDate(timeStamp);  
        Date today = new Date();  
        if(d1.getTime()>=today.getTime()){  
            return true;  
        }  
        return false;  
    }  
  
      
      
    /** 
     * HH:mm:ss格式时间转换为1970-01-01日的时间戳(也就是只有时间没有日期的情况要求使用时间戳表示时间) 
     * @author DingJiaCheng 
     * */  
    public static int transFromTime(String time){  
        return transForMilliSecond("1970-01-01 "+time,"yyyy-mm-dd HH:mm:ss");  
    }  
      
    /** 
     * 时间戳转换为HH:mm:ss格式时间(日期去除) 
     * @author DingJiaCheng 
     * */  
    public static String transToTime(int time){  
        String s = new String(transForDate1(time));  
        String ss[] = s.split(" ");  
        return ss[1];  
    }  
      
    public static int transToChuo(String dateString){  
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");  
        int res = 0;  
        try {  
            Date date=simpleDateFormat .parse(dateString);  
            res = (int) date.getTime();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return res;  
    }  
      
    // 获取当前月的第一天
    public static Integer getTheFirstDayOfTheCurrentMonth() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar  = Calendar.getInstance();//获取当前日期
    calendar .set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
    calendar .set(Calendar.HOUR_OF_DAY,0); // 将小时置0
    calendar.set(Calendar.MINUTE,0); // 将分钟置0
    calendar.set(Calendar.SECOND,0); // 将秒置0
    calendar.set(Calendar.MILLISECOND,0);
    String firstDay = format.format(calendar .getTime());  // 得到时间字符
    System.out.println(firstDay);
    Integer newFirstDay = DateFormatUtil.transForMilliSecond(firstDay); // 将时间字符转化成时间戳
    return newFirstDay;
    }
    
    // 获取当前月的最后一天
    public static Integer getTheLastDayOfTheCurrentMonth() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar  = Calendar.getInstance();//获取当前日期
    calendar.add(Calendar.MONTH, 1); // 当前月份加1,得到下一月份
    calendar .set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
    calendar .set(Calendar.HOUR_OF_DAY,0); // 将小时置0
    calendar.set(Calendar.MINUTE,0); // 将分钟置0
    calendar.set(Calendar.SECOND,-1); // 将秒减一     得到的 23:59:59
    calendar.set(Calendar.MILLISECOND,0);
    String lastDay = format.format(calendar.getTime());
    System.out.println(lastDay);
    Integer newFirstDay = DateFormatUtil.transForMilliSecond(lastDay); // 将时间字符转化成时间戳
   
    return newFirstDay;
    }
    
    
    public static void main(String[] args) {  
          
        //System.out.println(getIntegralTimeEnd());  
        //System.out.println(transForDate2(transForMilliSecond("2015-02-25 00:00:00")));  
        //System.out.println(transForMilliSecond("2016-01-25","yyyy-mm-dd"));  
        //System.out.println(transForDate1(transForMilliSecond("1970-01-01 00:00:00","yyyy-mm-dd HH:mm:ss")));  
        //System.out.println(currentTimeStamp());  
        //System.out.println(transForDate(currentTimeStamp()));  
        //System.out.println(new Date());  
        //System.out.println(DateUtils.getDate());  
        //System.out.println(transFromTime("00:00:01"));  
        //System.out.println(transToTime(transFromTime("15:01:13")));  
   
    /*Date date = new Date();
      String str = DateFormatUtil.formatDate(date,"yyyyMMddHHmmss");
     
      int it = (int) Math.round(Math.random()*(99999-10000)+10000);
      String name = str+"_"+it+".";
     
    System.out.println(name);
   
    File file = new File("HelloWorld.java");  
        String fileName = file.getName();  
        String suffix = fileName.substring(fileName.lastIndexOf("."));  
        System.out.println(suffix);  */
   
    // 获取一个时间段
    /*String time = "2018-05-11 00:00:00 - 2018-05-19 00:00:00";
    String time_1 = time.substring(0,20);
    String time_2 = time.substring(22, 41);
    Integer date_1 = DateFormatUtil.transForMilliSecond(time_1, "yyyy-MM-dd HH:mm:ss");
    Integer date_2 = DateFormatUtil.transForMilliSecond(time_2, "yyyy-MM-dd HH:mm:ss");
   
    System.out.println(time_1 + "::::::" + time_2);
    System.out.println(date_1 + "######" + date_2);*/
   
   
    }
}
<think> 我们正在讨论Delphi中时间字符串时间戳的相互换。 根据用户提供的引用[1]中的代码片段,它展示了一个将时间字符串换为时间戳的函数,其中使用了`Datetimetounix`和`IncHour`等函数。 但是,用户要求的是相互换的方法,因此我们还需要时间戳时间字符串的方法。 在Delphi中,时间戳通常指的是Unix时间戳(即自1970-01-01 00:00:00 UTC以来的秒数)。 步骤: 1. 时间字符串时间戳(String to Unix Timestamp): 需要将字符串解析为TDateTime,然后调整时区(如果需要),再换为Unix时间戳。 注意:Delphi的`StrToDateTime`默认使用系统格式,可能需要处理格式问题。 2. 时间戳时间字符串(Unix Timestamp to String): 将Unix时间戳换为TDateTime,然后使用`DateTimeToStr`或`FormatDateTime`格式化为字符串。 需要注意的是,时区问题:Unix时间戳是UTC时间,而TDateTime可能是本地时间。因此,在换时要考虑时区偏移。 引用[1]中的函数Gettimestamp将输入字符串换为TDateTime后,减去了8小时(可能是从UTC+8到UTC),然后换为Unix时间戳。 下面我们分别给出两个方向的换函数,并考虑时区处理。 假设我们的时间字符串是本地时间(如北京时间,UTC+8),那么在换为时间戳时需要减去8小时(即换为UTC时间),反之在将时间戳换为字符串时需要加上8小时(换为本地时间)。 但是,时区偏移可能因地区而异,我们可以使用系统时区信息来避免硬编码。Delphi中可以使用`TTimeZone`类(在System.DateUtils单元)来处理时区。 然而,如果用户使用的是较老的Delphi版本(如Delphi 7)可能没有`TTimeZone`,那么可能需要手动设置时区偏移。这里我们提供两种方法:一种是固定时区偏移(如引用[1]中的-8),另一种是使用系统时区(需要较新版本)。 为了通用性,我们首先给出固定时区偏移的方法,然后再给出使用`TTimeZone`的方法。 方法1:固定时区偏移(假设本地时间是UTC+8) 时间字符串时间戳: - 将字符串换为TDateTime(使用StrToDateTime,注意格式) - 减去8小时(因为TDateTime值被认为是本地时间,而Unix时间戳是UTC) - 调用DateTimeToUnix得到时间戳 时间戳时间字符串: - 将时间戳换为TDateTime(使用UnixToDateTime,得到的是UTC时间) - 加上8小时(换为本地时间) - 使用DateTimeToStr或FormatDateTime换为字符串 方法2:使用TTimeZone(Delphi XE以上版本) 使用`TTimeZone.Local.UtcOffset`获取本地时区UTC的偏移量(单位为小时,注意有正负)。 下面我们分别编写函数: 注意:由于时间字符串换涉及格式问题,建议使用StrToDateTimeEx或设置格式,或者使用FormatSettings来指定日期时间格式,以避免换错误。这里为了简单,我们假设字符串格式系统设置一致。 我们首先使用方法1(固定时区)来实现,然后使用方法2(动态时区)。 另外,用户提供的函数中使用了`IncHour`,这是DateUtils单元中的函数,我们需要在uses中加入DateUtils(对于固定偏移)或同时加入System.DateUtils(对于TTimeZone)。 由于用户可能使用不同版本,这里我们尽量兼顾。 下面给出代码示例: 方法1:固定时区偏移(假设为UTC+8) ``` uses SysUtils, DateUtils; // 需要DateUtils单元 // 时间字符串(本地时间,UTC+8)时间戳 function DateTimeStrToTimestamp(const DateTimeStr: string): Int64; var LDateTime: TDateTime; begin LDateTime := StrToDateTime(DateTimeStr); // 注意:这里需要字符串格式系统设置匹配 // 将本地时间(假设为UTC+8)换为UTC时间:减去8小时 LDateTime := IncHour(LDateTime, -8); Result := DateTimeToUnix(LDateTime); end; // 时间戳时间字符串(本地时间,UTC+8) function TimestampToDateTimeStr(const Timestamp: Int64): string; var LDateTime: TDateTime; begin LDateTime := UnixToDateTime(Timestamp); // 换得到UTC时间 // 将UTC时间换为本地时间(假设UTC+8):加上8小时 LDateTime := IncHour(LDateTime, 8); Result := DateTimeToStr(LDateTime); end; ``` 方法2:使用TTimeZone(动态获取时区偏移) 注意:TTimeZone在System.DateUtils单元(Delphi XE以上) ``` uses SysUtils, DateUtils, System.DateUtils; // System.DateUtils中有TTimeZone // 时间字符串(本地时间时间戳 function DateTimeStrToTimestamp2(const DateTimeStr: string): Int64; var LDateTime: TDateTime; Offset: TDateTime; begin LDateTime := StrToDateTime(DateTimeStr); // 获取本地时区UTC的偏移(小时),并换为TDateTime(小时/24) Offset := TTimeZone.Local.UtcOffset.TotalHours / 24; // 将本地时间换为UTC时间:减去偏移 LDateTime := LDateTime - Offset; Result := DateTimeToUnix(LDateTime); end; // 时间戳时间字符串(本地时间) function TimestampToDateTimeStr2(const Timestamp: Int64): string; var LDateTime: TDateTime; Offset: TDateTime; begin LDateTime := UnixToDateTime(Timestamp); // 得到UTC时间 Offset := TTimeZone.Local.UtcOffset.TotalHours / 24; LDateTime := LDateTime + Offset; // 换为本地时间 Result := DateTimeToStr(LDateTime); end; ``` 注意:TTimeZone.UtcOffset返回的是TTimeSpan,我们可以用TotalHours来获取小时数(包括小数),然后换为天数(因为TDateTime中一天为1)。 另外,由于时间字符串换可能因格式问题出错,建议在实际使用时使用带格式的换函数,如: - 使用StrToDateTimeEx,或者使用FormatSettings指定格式。 - 或者使用TFormatSettings.Create来设置特定的格式。 例如,如果时间字符串是'yyyy-mm-dd hh:nn:ss'格式,我们可以这样: ``` var FormatSettings: TFormatSettings; begin FormatSettings := TFormatSettings.Create; FormatSettings.ShortDateFormat := 'yyyy-mm-dd'; FormatSettings.LongTimeFormat := 'hh:nn:ss'; // 然后使用 LDateTime := StrToDateTime(DateTimeStr, FormatSettings); ``` 根据用户需求,我们提供了两种换方法。用户可以根据自己的Delphi版本和需求选择。 另外,用户提供的引用代码中使用了`IncHour`,我们这里也使用了同样的函数(在DateUtils中)。如果用户使用的Delphi版本较低(如Delphi7)没有`IncHour`,可以使用`LDateTime := LDateTime - 8/24;`来减去8小时。 最后,我们提供一个兼容低版本的方法(不使用IncHour): ``` // 方法1的替代(不使用IncHour) function DateTimeStrToTimestamp(const DateTimeStr: string): Int64; var LDateTime: TDateTime; begin LDateTime := StrToDateTime(DateTimeStr); // 减去8小时:8小时等于8/24天 LDateTime := LDateTime - 8/24; Result := DateTimeToUnix(LDateTime); end; ``` 同理,加8小时可以用`LDateTime + 8/24`。 总结: - 时间字符串时间戳:先TDateTime,减去时区偏移(换为UTC),再调用DateTimeToUnix。 - 时间戳时间字符串:先UnixToDateTime得到UTC时间,加上时区偏移(换为本地时间),再字符串。 注意:时区偏移的方向(本地时间=UTC+偏移),所以时间戳时减去偏移,字符串时加上偏移。 请用户根据实际情况调整时区偏移量(例如,如果是UTC+8则偏移为8小时,UTC-5则偏移为-5小时)。 另外,如果时间字符串已经是UTC时间,则不需要加减时区偏移。 以上代码示例仅供参考,具体实现可能需要根据实际情况调整。 现在,我们为用户生成相关问题: </think> ### Delphi 时间字符串时间戳相互换方法 在 Delphi 中实现时间字符串 Unix 时间戳的相互换,主要涉及以下核心函数(需在 `uses` 中添加 `SysUtils, DateUtils`): #### 1. 时间字符串 → Unix 时间戳 ```delphi function StrToTimestamp(const DateTimeStr: string): Int64; var LocalTime: TDateTime; begin // 将字符串为 TDateTime(按系统格式解析) LocalTime := StrToDateTime(DateTimeStr); // 换为 UTC 时间(假设原字符串是 UTC+8 时区) LocalTime := IncHour(LocalTime, -8); // 为 Unix 时间戳(1970-01-01 起的秒数) Result := DateTimeToUnix(LocalTime); end; ``` **说明**: - `IncHour(LocalTime, -8)`:减去 8 小时(若原始时间为 UTC+8 时区) - 使用时需确保输入格式系统设置匹配(如 `'2023-01-01 12:00:00'`) #### 2. Unix 时间戳时间字符串 ```delphi function TimestampToStr(const Timestamp: Int64): string; var UTCTime, LocalTime: TDateTime; begin // 时间戳 UTC 时间 UTCTime := UnixToDateTime(Timestamp); // UTC 本地时间(UTC+8) LocalTime := IncHour(UTCTime, 8); // 格式化为字符串 Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', LocalTime); end; ``` **说明**: - `FormatDateTime` 可自定义格式,如 `'dd/mm/yyyy hh:nn'` - `IncHour(..., 8)`:添加时区偏移(根据实际时区调整) #### 使用示例 ```delphi var Timestamp: Int64; TimeStr: string; begin // 字符串时间戳 Timestamp := StrToTimestamp('2023-07-20 14:30:00'); ShowMessage('时间戳: ' + IntToStr(Timestamp)); // 输出如 1689846600 // 时间戳字符串 TimeStr := TimestampToStr(1689846600); ShowMessage('时间: ' + TimeStr); // 输出 2023-07-20 14:30:00 end; ``` #### 关键注意事项 1. **时区处理**: - 上述代码假设本地时区为 **UTC+8**(中国标准时间) - 修改 `IncHour` 参数可适配其他时区(如 UTC-5 用 `IncHour(..., -5)`) 2. **格式兼容**: - 使用 `StrToDateTime` 需系统区域设置输入格式一致 - 若格式固定,建议用 `StrToDateTime('2023-01-01', FormatSettings)` 指定格式 3. **精度**: - Unix 时间戳单位为**秒**(32/64位整数) - 毫秒级时间戳需除以 1000 并处理余数[^1]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值