如何快速设置当前时间? [英] How to set current time in swift?
问题描述
我正在尝试将纯 Java 代码转换为 swift.但是,我在设置当前时间时遇到了一点问题.我可以以毫秒为单位获取当前时间.但是我无法设置当前时间.有什么帮助吗?
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?
这是我的代码
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代码
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);
}
}
在 swift 中设置当前时间的任何帮助.我几乎接近我的答案.
Any help with setting the current time in swift.I am almost closing to my answer.
推荐答案
在您的代码中,您想为 1970 年以来的时间添加秒数.您很幸运,有一个初始化程序:NSDate(timeIntervalSince1970:NSTimeInterval)
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)
这将创建一个新的 NSDate
并将 86400000
秒添加到自 1970 年以来的秒数.
This will create a new NSDate
and add 86400000
seconds to the time in seconds right now since 1970.
这篇关于如何快速设置当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!