2016-04-27 11 views
1

これを迅速に書く方法は見つけられませんでしたが、今年と今年の終わりの日付の違いはどうすればわかりますか?私はjavaでこれを行ったが、迅速に同じことをする方法を見つけることができませんでした。ここに私が書いたJavaロジックがあります:スイフト:日付の差

 Calendar today = Calendar.getInstance(); 
     Calendar endOfYear = Calendar.getInstance(); 
     endOfYear.setTime(new Date(0)); 
     endOfYear.set(Calendar.DAY_OF_MONTH, 31); 
     endOfYear.set(Calendar.MONTH, 11); 
     endOfYear.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR)); 

     double t = endOfYear.getTimeInMillis() - today.getTimeInMillis(); 
     String time = new SimpleDateFormat("0:ss", Locale.US).format(t); 

これはもちろん、私が迅速にやろうとしている秒数を出力します。

UPDATE:

私が持っているすべては、次のとおりです。

func timer() { 
    let time = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.MediumStyle) 
    timeLabel.text = "\(time)" 
} 

そして、この私が望んでいないだけで全体の時間...

+1

これはコードリファクタリングサイトではないので、あなたが間違っていることを理解できるように、あなたの 'swift'コードを追加することができれば素晴らしいでしょう。 –

+0

更新があります –

答えて

0

あなたはNSDateの2つのインスタンスを作成し、次にあなたCFDateGetIntervalSinceDate(current_time, year_end)

これはあなたが欲しいものに似ています(あまり正確ではありませんが、正確な年末時間と秒を含む日付):

let dateFormatter = NSDateFormatter() 
dateFormatter.dateFormat = "dd-mm-yyyy" 
let currentTime = NSDate() 
let yearEnd = dateFormatter.dateFromString("31-12-2016") 
let interval = CFDateGetTimeIntervalSinceDate(currentTime, yearEnd) 
print("\(Int(interval)) seconds left until the year's end") 
+0

私が書いたサンプルコードのようにコードをharcodingするのではなく、プログラムで年を設定する方法はありますか? –

+0

私の例はプリミティブメソッドを使用していました。私はあなたが年末を自動的に得ることができると確信しています。 ** NSDate **と** NSCalendar **の文書をチェックしてください。 – Lawrence413

1

は私にいくつかの時間がかかりましたが、これは私が探していたものです。

let date = NSDate() 
    let calendar = NSCalendar.currentCalendar() 
    let components = calendar.components([.Day, .Month, .Year, .Hour, .Minute, .Second, .Nanosecond], fromDate: date) 
    let now = NSCalendar.currentCalendar().dateWithEra(1, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond)! 
    let newYears = NSCalendar.currentCalendar().dateWithEra(1, year: components.year, month: 12, day: 31, hour: 01, minute: 00, second: 00, nanosecond: 00)! 


    let units: NSCalendarUnit = [.Day, .Month, .Year, .Hour, .Minute, .Second] 
    let difference = NSCalendar.currentCalendar().components(units, fromDate: now, toDate: newYears, options: []) 

    let seconds = difference.second 

これはthisどこに似た形式のタイマー一種として示しn日、n時間、n分、n秒です。 ありがとう!