
十里(5km)macOS 开发
swift获取系统当前时间
想做个 macOS 小工具生成 645 协议的广播校时报文,结果被「怎么获取当前时间」卡住,搜到的方法全过时了。本文用 Playground 演示了 Swift 里用 Date 和 Calendar 取出年月日时分秒的最新写法。
0次点击1分钟阅读
今天尝试做一个macOS下的生成645协议的广播校时报文的小工具,做到一半竟然被“如何获取当前时间?”给难住了,百度搜索结果找来的方法都是过时的,经过尝试和研究找到了方法。
以在macOS的playground为例,首先新建一个macOS平台的playground,编写代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15//: Playground - noun: a place where people can play import Cocoa // 获取当前时间 let now: Date = Date() let calendar = Calendar.current; let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now) // 获取当前时间对应年月日时分秒的整数值 let year = components.year! % 100 let month = components.month let day = components.day let hour = components.hour let minute = components.minute let second = components.second
就会看到如下的结果:



