java - swift : Date difference

标签 java ios swift time

我找不到快速编写此代码的方法,但如何获取现在和年底之间的日期差异?我已经在 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)"
}

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

最佳答案

花了我一些时间,但这正是我要找的:

    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 秒。 不过谢谢!

关于java - swift : Date difference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36883463/

相关文章:

ios - 是否有类似于 PC/Mac 世界的 iOS 基准测试程序?

objective-c - 在 xcodebuild 期间找不到 RestKit/RestKit.h' 文件错误

ios - 可本地化的字符串!!!! bundle (路径)尚未加载

ios - 如何在后台运行 iOS 应用程序来解析海量数据 API?

java - 如果第一个为真,则执行逻辑或忽略第二个语句

java - Java中的 volatile 与静态

ios - 如何创建一个带有可选辅助 View 参数的 SwiftUI View ?

java - 在多个 JPanel 中绘图

java - Netty 4.0.0.CR9 中的 AIO

swift - 无法在单独的文件中扩展嵌套结构