如何在ios中获取今天日期的开始和结束时间? [英] how to get start and end time of today's date in ios?

查看:1184
本文介绍了如何在ios中获取今天日期的开始和结束时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用此代码获取当前日期和时间

I am getting current date and time by using this code

    let today: NSDate = NSDate()
    let dateFormatter: NSDateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "SGT");
    print(dateFormatter.stringFromDate(today))

但我希望获得开始时间和今天结束时间

but i want to get start time and end time of today’s date

示例:
12-09-2016 00:00:00和12-09-2016 23: 59:59

如何获取当前日期的开始和结束时间?

How to get start and end time of current date?

推荐答案

您可以使用 startOfDayForDate 获取今天的午夜日期,然后从该日期算起结束时间。

You can use startOfDayForDate to get today's midnight date and then get end time from that date.

//For Start Date
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(abbreviation: "UTC")! //OR NSTimeZone.localTimeZone()
let dateAtMidnight = calendar.startOfDayForDate(NSDate())

//For End Date
let components = NSDateComponents()
components.day = 1
components.second = -1
let dateAtEnd = calendar.dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions())
print(dateAtMidnight)
print(dateAtEnd)

编辑:将日期转换为字符串

let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone (abbreviation: "UTC")! // OR NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let startDateStr = dateFormatter.stringFromDate(dateAtMidnight)
let endDateStr = dateFormatter.stringFromDate(dateAtEnd)
print(startDateStr)
print(endDateStr)

这篇关于如何在ios中获取今天日期的开始和结束时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆