如何在swift中设置当前时间?

时间:2015-07-07 08:38:15

标签: java ios swift nsdate

我正在尝试将纯Java代码转换为swift.But,我在设置当前时间时遇到了一些问题。我可以用毫秒来获取当前时间。但我无法设置当前时间。对此有何帮助?

这是我的代码

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.
}
}

这是我要转换为swift代码的java代码

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);
    }
}

在swift中设置当前时间的任何帮助。我几乎接近我的答案。

1 个答案:

答案 0 :(得分:0)

在您的代码中,您希望在1970年以后添加秒数。您很幸运,有一个初始化程序:NSDate(timeIntervalSince1970: NSTimeInterval)

let now = NSDate(timeIntervalSince1970: 86400000)

这将创建一个新的NSDate并添加86400000秒,直到1970年以来的秒数。