How to set current time in swift?

丶灬走出姿态 提交于 2019-12-13 09:19:37

问题


I am trying to convert pure java code into swift.But,I am having a little problem with setting the current time.I can get the current time in milliseconds.But I cant set the current time.Any help with that?

Here is my code

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    let now = NSDate()

    var auctionDate = [String:String]()

    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US")

    var sdfDDMMYYYYEEE : NSDateFormatter!
    sdfDDMMYYYYEEE.dateFormat = "dd/MM/yyyy (EEE)"

    var sdfDDMMYYYY : NSDateFormatter!
    sdfDDMMYYYY.dateFormat = "dd/MM/yyyy"

    var sdfEEE : NSDateFormatter!
    sdfEEE.dateFormat = "EEE"

    // This is how i get the current time
    println((now.timeIntervalSince1970)*1000 + 86400000.00)

    for var i = 0; i < 5; i++ {
        if sdfEEE.stringFromDate(now) == "Sun" {
            // This is where i have to set my time with that ((now.timeIntervalSince1970)*1000 + 86400000.00)
            i--;
            continue;
        }
        auctionDate[(sdfDDMMYYYY.stringFromDate(now) as String)] = (sdfDDMMYYYYEEE.stringFromDate(now) as String)
        // Here too I have to set my time
    }

    println(dateFormatter.stringFromDate(now))

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Here is the java code that I want to convert into swift code

import java.text.*;
import java.util.*;
public class DateTest{

    Date now = new Date();
    Map<String, String> myDate = new LinkedHashMap<String, String>();
    myDate.put("", "All");
    SimpleDateFormat sdfDDMMYYYYEEE = new SimpleDateFormat("dd/MM/yyyy (EEE)");
    SimpleDateFormat sdfDDMMYYYY = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdfEEE = new SimpleDateFormat("EEE");
    for (int i = 0; i < 5; i++) {
        if (sdfEEE.format(now).equals("Sun")) {
            now.setTime(now.getTime() + 86400000);
            i--;
            continue;
        }
        myDate.put(sdfDDMMYYYY.format(now), sdfDDMMYYYYEEE.format(now));
        now.setTime(now.getTime() + 86400000);
    }
}

Any help with setting the current time in swift.I am almost closing to my answer.


回答1:


In your code you want to add seconds to time eince 1970. You're in luck, there is an initializer for that: NSDate(timeIntervalSince1970: NSTimeInterval)

let now = NSDate(timeIntervalSince1970: 86400000)

This will create a new NSDate and add 86400000 seconds to the time in seconds right now since 1970.



来源:https://stackoverflow.com/questions/31263690/how-to-set-current-time-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!