LoginSignup
13
13

More than 5 years have passed since last update.

[Swift]AnyObjectではなくIntで現在時刻を取得する

Posted at

現在時刻を取得する

let now = NSDate() // 現在日時の取得
let dateFormatter = NSDateFormatter()

dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") // ロケールの設定

dateFormatter.timeStyle = .MediumStyle
dateFormatter.dateStyle = .MediumStyle
println(dateFormatter.stringFromDate(now)) // -> "2014/11/02 10:32:22"

日付を取って、時刻だけ残す

var strArray:NSArray = dateFormatter.stringFromDate(now).componentsSeparatedByString("/")[2].componentsSeparatedByString(" ")[1].componentsSeparatedByString(":")
// -> ["10", "32", "22"]

時間、分、秒の値をそれぞれ配列に入れることができた。

一桁だったら頭に0をつけたい

時間(hour)が一桁の場合(ex.8時)、「8」だけになる。これを「08」と表示したいと思った。

数値比較を試みる
数値を比較して条件を分けて、先頭に「0」足すことを考える。

strArray[0] < 10

「Cannot invoke '<' with an argument list of type '(AnyObject,IntegerLiteralConvertible」とエラーが出る。時間が入っている「strArray[0]」はAnyObjectみたいなので、型変換が必要だ。

AnyObjectをIntに変換したいが・・・
swift
strArray[0] as? Int // -> nil
strArray[0] as? NSInteger // -> nil

しかしなぜかnilになってしまい、if文で判定することができなかった。

NSCalendarを使う

let date = NSDate() // -> "Nov 2, 2014, 10:32 AM"
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date)
let hour = components.hour // -> 10
let minutes = components.minute // -> 32
let second = components.second // -> 22

hour,minutes,secondはIntなので、大小比較ができた。これを使えば、先頭に「0」をつけることができました。

参考
How to get the current time(and hour) as datetime - Swift
[Swift]NSDateComponentで日付の各要素を取得

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13