開始使用免費開始

日期格式(2)

你不僅可以把字元轉成日期,還可以把已經是日期的物件轉成不同格式的日期,方法是使用 format()

# 股市史上最佳單日點數漲幅。道瓊上漲了 936 點!
best_date
[1] "2008-10-13"

format(best_date, format = "%Y/%m/%d")
[1] "2008/10/13"

format(best_date, format = "%B %d, %Y")
[1] "October 13, 2008"

提醒你,常見的格式符號如下:

  • %Y:4 位數年份(1982)
  • %y:2 位數年份(82)
  • %m:2 位數月份(01)
  • %d:2 位數日期(13)
  • %A:星期幾(Wednesday)
  • %a:星期縮寫(Wed)
  • %B:月份(January)
  • %b:月份縮寫(Jan)

本練習屬於課程

R 金融中級

檢視課程

練習說明

  • char_date 建立向量 dates,並指定正確的 format,讓 R 能正確讀取。
  • 使用 format() 調整 dates,讓每個日期呈現為 "Jan 04, 17"
  • 再使用 format() 調整 dates,讓每個日期呈現為 "01,04,2017"

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

char_dates <- c("1jan17", "2jan17", "3jan17", "4jan17", "5jan17")

# Create dates using as.Date() and the correct format 
dates <- ___

# Use format() to go from "2017-01-04" -> "Jan 04, 17"
___

# Use format() to go from "2017-01-04" -> "01,04,2017"
___
編輯並執行程式碼