iT邦幫忙

0

swift 日期

  • 分享至 

  • xImage
  •  
  1. class ViewController 放入
let myFormatter = DateFormatter() // 建立一個 DateFormatter 用來處理日期與字串的轉換
var currentDate :Date = Date() // 定義一個目前日期變數,預設為程式啟動時的當前日期

var days :[String]! = [] // 存放資料庫中每個記錄的日期(字串)
var myRecords :[String:[[String:String]]]! = [:] 
// 以日期字串作為 key,對應一個陣列,每個元素是一筆記錄(以字典存放欄位資訊)
var eachDayAmount :[String:Double] = [:] // 以日期作為 key,記錄每天的總計金額

var currentMonthLabel :UILabel! // 當前月份的標籤

(((以下皆在class ViewController內)))
2. override func viewDidLoad() 放入

// 目前年月
currentMonthLabel = UILabel(frame: CGRect(x: 0, y: 0, width: fullsize.width * 0.7, height: 50)) // 建立一個 UILabel 並設定其大小、位置、文字顏色、字型與標籤
currentMonthLabel.center = CGPoint(x: fullsize.width * 0.5, y: 35)
currentMonthLabel.textColor = UIColor.white
myFormatter.dateFormat = "yyyy 年 MM 月" // 使用 DateFormatter 將目前日期格式化成 "yyyy 年 MM 月",顯示在標籤上
currentMonthLabel.text = myFormatter.string(from: currentDate)
currentMonthLabel.textAlignment = .center
currentMonthLabel.font = UIFont(name: "Helvetica Light", size: 32.0)
currentMonthLabel.tag = 701
self.view.addSubview(currentMonthLabel)

  1. 重寫 viewWillAppear,在畫面每次出現前執行
    從 UserDefaults 取得先前設定的顯示年月字串,
    如果有值則用 DateFormatter 將其轉換為日期,並更新 currentDate
    更新後將 "displayYearMonth" 清空,以免重複使用
override func viewWillAppear(_ animated: Bool) {
    let displayYearMonth = myUserDefaults.object(forKey: "displayYearMonth") as? String
    if displayYearMonth != nil && displayYearMonth != "" {
        myFormatter.dateFormat = "yyyy-MM"
        currentDate = myFormatter.date(from: displayYearMonth!)!
            
        myUserDefaults.set("", forKey: "displayYearMonth")
        myUserDefaults.synchronize()
    }
        
    self.updateRecordsList()
    // 呼叫 updateRecordsList() 方法,更新並重新載入 table view 中的資料
}
  1. func updateRecordsList()放入
// 設定日期格式為 "yyyy-MM",將 currentDate 轉換成字串(例如 "2025-02")
myFormatter.dateFormat = "yyyy-MM"
let yearMonth = myFormatter.string(from: currentDate)


// 重新格式化日期顯示,並更新當前月份標籤
myFormatter.dateFormat = "yyyy 年 MM 月"
currentMonthLabel.text = myFormatter.string(from: currentDate)
  1. 切換月份,傳入一個 DateComponents(例如 month 改變 ±1),
    透過 Calendar 計算新的日期,更新 currentDate,並重新讀取資料更新列表
func updateCurrentDate(_ dateComponents :DateComponents) {
    let cal = Calendar.current
    let newDate = (cal as NSCalendar).date(byAdding: dateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))
        
    currentDate = newDate!
        
    self.updateRecordsList()
}

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言