美文网首页
参数为多个日期时间的数组,返回离当前时间最近的那个时间

参数为多个日期时间的数组,返回离当前时间最近的那个时间

作者: Mr_dreamer | 来源:发表于2020-02-18 21:41 被阅读0次

    php

    $date = [
        '2019-12-31 12:22:33',
        '2019-11-10 12:22:22',
        '2018-12-01 12:22:33',
        '2019-05-11 11:11:11'
    ];
    
    $now = time();
    
    function getNearDate($date, $com){
        $cnt = count($date);  
        if ($cnt === 0) return false;
        for($i=0 ; $i < $cnt; $i++){
            if(isset($date[$i+1])) {           
                $front = abs($com - strtotime($date[$i]));
                $behind = abs($com - strtotime($date[$i+1]));          
                if($front < $behind) {
                    list($date[$i], $date[$i+1]) = [$date[$i+1], $date[$i]];
                }
            }
        }
    
        return end($date);
    }
    
    var_dump(getNearDate($date, $now));
    

    golang

    package main
    
    import (
        "fmt"
        "time"
        "errors"
    )
    
    func main() {
        arr := [] string { 
            "2019-12-31 12:22:33",
            "2019-11-10 12:22:22",
            "2018-12-01 12:22:33",
            "2019-05-11 11:11:11"}
            
    
        now := time.Now().Unix()
    
        res, err := getNearDate(arr, now)
        if err != nil {
            panic(err)
        }
    
        fmt.Println(res)
    }
    
    func getNearDate(date_arr []string, timestamp int64) (string,error) {
        
        cnt := len(date_arr)
        if cnt == 0 {
            return "输入非法",errors.New("输入非法")
        }
    
        for i:=0; i<cnt;i++ {
            if i < cnt-1 {
                before := Int64abs(timestamp - strtotime(date_arr[i]))
                behind := Int64abs(timestamp - strtotime(date_arr[i+1]))
                if before < behind {
                    temp := date_arr[i]
                    date_arr[i] = date_arr[i+1]
                    date_arr[i+1] = temp
                }
            }
        }
    
        return date_arr[cnt-1],nil
    }
    
    func strtotime(date string) int64 {
    
        timeLayout := "2006-01-02 15:04:05"                           
        loc, _ := time.LoadLocation("Local")                            
        theTime, _ := time.ParseInLocation(timeLayout, date, loc) 
        sr := theTime.Unix()                                          
        return sr
    }
    
    func Int64abs (num int64) int64 {
        if num < 0 {
            return -num
        }
        return num
    }
    

    相关文章

      网友评论

          本文标题:参数为多个日期时间的数组,返回离当前时间最近的那个时间

          本文链接:https://www.haomeiwen.com/subject/sawboctx.html