斯威夫特:日期差异

时间:2016-04-27 07:45:00

标签: java ios swift time

我无法在swift中找到一种方法来写这个,但我如何才能看到现在和年底之间的日期差异?我已经在java中完成了这个,但是无法在swift中找到一种方法。这是我写的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);

这当然只输出了我在swift中尝试做的秒数。

更新:

我只有:

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

这就是我不想要的整个时间......

2 个答案:

答案 0 :(得分: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秒。  谢谢!

答案 1 :(得分: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")