我有这个用swift写的应用程序,我分别得到一个未来的日期和未来的小时(作为Unix时间戳),我想把它们变成一个Date()对象,这样我就可以转换为Unix时间戳。
如果您现在另一种直接转换为Unix时间戳的方式可以随意发布。
答案 0 :(得分:1)
这可能会为您提供有关如何实现目标的一些想法:
let calendar = Calendar.current
let currentDate = Date()
// Random future date, 1 month from now
let futureDate = calendar.date(byAdding: .month, value: 1, to: currentDate)!
let futureDateComponents = calendar.dateComponents([.year, .month, .day], from: futureDate)
// Random hour
let futureHour = 2
// Use your future date and your future hour to set the components for the new date to be created
var newDateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: currentDate)
newDateComponents.year = futureDateComponents.year
newDateComponents.month = futureDateComponents.month
newDateComponents.day = futureDateComponents.day
newDateComponents.hour = futureHour
newDateComponents.minute = 0
newDateComponents.second = 0
// Create a new date from components
let newDate = calendar.date(from: newDateComponents)!
// Convert new date to unix time format
let unixTime = newDate.timeIntervalSince1970
print(newDate) // 2018-03-06 02:00:00 +0000
print(unixTime) // 1520301600.0
请注意,在实际项目中,您应该避免强行展开(即使用'!')。
答案 1 :(得分:0)
如果您的日期字符串格式为dd-MM-yyyy
,则可以将其转换为Date
对象,如下所示:
let string = "02-06-2018"
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX") // this is only needed if string is always gregorian but you don't know what locale the device is using
guard let date = formatter.date(from: string) else {
// handle error however you'd like
return
}
或者,如果您已有Date
个对象,则不需要上述内容。但是,无论如何,只要您拥有Date
,就可以通过设置小时,分钟和秒来获得Date
,如下所示:
let hour = 14 // 2pm
guard let result = Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: date) else {
// handle error however you'd like
return
}