2016-09-26 51 views

回答

5

嘗試發送這樣的:

convert.to.date <- function(d) { 
    if(is.na(strptime(d, '%Y-%m-%d %H:%M:%S'))) stop("Format incorrect") 
    return(format(d, format='%Y-%m-%d %H:%M:%S', usetz = FALSE)) 
} 

convert.to.date('2002-09-04 16:45:40') 
#[1] "2002-09-04 16:45:40" 
convert.to.date('09-04-2002 16:45:40') 
#Error in convert.to.date("09-04-2002 16:45:40") : Format incorrect 
1

那麼,你可以編寫一個函數來檢查日期的格式輸入您所使用as.Date函數指定format參數

checkDateFormat <- function(input) { 
    x <- as.Date(input, format= "%Y-%m-%d %H:%M:%S") 
    if(is.na(x)) 
    "Format incorrect" 
    else 
    "Format correct" 
} 

checkDateFormat("2002-09-04 16:45:40") 
#[1] "Format correct" 

checkDateFormat("2002-09-04") 
#[1] "Format incorrect" 

checkDateFormat("2002-09-04 16:45") 
#[1] "Format incorrect" 
+0

其實我只想使'checkDateFormat(「2002-09-04 16:45」)'是正確的。所以我在函數中刪除了':%s'。但是,當我使用'checkDateFormat(「2002-09-04 16:45:00」)'這應該是不正確的,但確實得到正確的結果。這裏發生了什麼? –

相關問題