Nsdate Beginning of Day and End of Day

NSDate beginning of day and end of day

You are missing NSDayCalendarUnit in

NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];

Neat way to get end of day for date?

A better way would be to get the start of the next day and subtract 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 second.

Do you get what I want to say? It's very hard to define the end of the day. 23:59 is certainly not the end of the day, there is almost a whole minute left until the next day. And even 23:59:59 is not the end of a day. Because there is an infinite amount of fraction seconds between this time and the start of the next day. As far as I know NSDate supports nanoseconds out of the box, so in the current implementation there are at least 1 000 000 000 possible NSDates between 23:59:59 and the next day.

That's why you should see if you can find a way to use the start of the next day.

For example, instead of if (startOfDay <= date && date <= endOfDay) you could use if (startOfDay <= date && date < startOfNextDay).

To calculate the start of the next day you have to use NSCalendar. In iOS8 Apple added a couple of nice methods to make these calculations short:

let calendar = NSCalendar.currentCalendar()
let startOfDay = calendar.startOfDayForDate(NSDate())
let startOfNextDay = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: startOfDay, options: nil)!

EDIT: Since you now state that you want to query a database you don't need to find the end of the day. Check if the date is on or after the start of the day, and before the start of the next day.

how to get start and end time of today's date in ios?

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)

Edit: Convert date to string

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)

Working out the start and end of a day. Swift

We can create a more generic function using the methods on NSCalendar:

func rangeOfPeriod(period: NSCalendarUnit, date: NSDate) -> (NSDate, NSDate) {
let calendar = NSCalendar.currentCalendar()
var startDate: NSDate? = nil

// let's ask calendar for the start of the period
calendar.rangeOfUnit(period, startDate: &startDate, interval: nil, forDate: date)

// end of this period is the start of the next period
let endDate = calendar.dateByAddingUnit(period, value: 1, toDate: startDate!, options: [])

// you can subtract 1 second if you want to make "Feb 1 00:00:00" into "Jan 31 23:59:59"
// let endDate2 = calendar.dateByAddingUnit(.Second, value: -1, toDate: endDate!, options: [])

return (startDate!, endDate!)
}

Called as

 print("\(rangeOfPeriod(.WeekOfYear, date: NSDate()))")
print("\(rangeOfPeriod(.Day, date: NSDate()))")

Putting it into your code:

public class Date {
let dateFormatter = NSDateFormatter()
let date = NSDate()
let calendar = NSCalendar.currentCalendar()

func rangeOfPeriod(period: NSCalendarUnit) -> (NSDate, NSDate) {
var startDate: NSDate? = nil

calendar.rangeOfUnit(period, startDate: &startDate, interval: nil, forDate: date)

let endDate = calendar.dateByAddingUnit(period, value: 1, toDate: startDate!, options: [])

return (startDate!, endDate!)
}

func calcStartAndEndDateForWeek() {
let (startOfWeek, endOfWeek) = rangeOfPeriod(.WeekOfYear)

print("Start of week = \(dateFormatter.stringFromDate(startOfWeek))")
print("End of the week = \(dateFormatter.stringFromDate(endOfWeek))")
}


func calcStartAndEndDateForDay() {
let (startOfDay, endOfDay) = rangeOfPeriod(.Day)

print("Start of day = \(dateFormatter.stringFromDate(startOfDay))")
print("End of the day = \(dateFormatter.stringFromDate(endOfDay))")
}

init() {
dateFormatter.dateFormat = "dd-MM-yyyy"
}
}

let myDate = Date()
myDate.calcStartAndEndDateForWeek()
myDate.calcStartAndEndDateForDay()

Get first day of week and last day in objective-c


NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

cal.firstWeekday = 2;// set first week day to Monday
// 1: Sunday, 2: Monday, ..., 7:Saturday

NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSCalendarUnitWeekOfYear
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfTheWeek holds the beginning of the week

endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval - 1];
// endOfWeek now holds the last second of the last week day

[cal rangeOfUnit:NSCalendarUnitDay
startDate:&endOfWeek
interval:NULL
forDate:endOfWeek];
// endOfWeek now holds the beginning of the last week day

testing:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterShortStyle;

NSLog(@"start: %@", [formatter stringFromDate:startOfTheWeek]);
NSLog(@"end: %@", [formatter stringFromDate:endOfWeek]);

prints

start: 12.10.15, 00:00
end: 18.10.15, 00:00

So Monday is the beginning of the week

if I set

cal.firstWeekday = 1;

it will print

start: 11.10.15, 00:00
end: 17.10.15, 00:00

Sunday is the first day of the week

first and last day of the current month in swift

You get the first day of the month simply with

let components = calendar.components([.Year, .Month], fromDate: date)
let startOfMonth = calendar.dateFromComponents(components)!
print(dateFormatter.stringFromDate(startOfMonth)) // 2015-11-01

To get the last day of the month, add one month and subtract one day:

let comps2 = NSDateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = calendar.dateByAddingComponents(comps2, toDate: startOfMonth, options: [])!
print(dateFormatter.stringFromDate(endOfMonth)) // 2015-11-30

Alternatively, use the rangeOfUnit method which gives you
the start and the length of the month:

var startOfMonth : NSDate?
var lengthOfMonth : NSTimeInterval = 0
calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: &lengthOfMonth, forDate: date)

For a date on the last day of month, add the length of the month minus one second:

let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)

Updated for Swift5:

extension Date {
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}

var startOfMonth: Date {

let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month], from: self)

return calendar.date(from: components)!
}

var endOfDay: Date {
var components = DateComponents()
components.day = 1
components.second = -1
return Calendar.current.date(byAdding: components, to: startOfDay)!
}

var endOfMonth: Date {
var components = DateComponents()
components.month = 1
components.second = -1
return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)!
}

func isMonday() -> Bool {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: self)
return components.weekday == 2
}
}

How to get start and end of day in Javascript?


var start = new Date();
start.setUTCHours(0,0,0,0);

var end = new Date();
end.setUTCHours(23,59,59,999);

alert( start.toUTCString() + ':' + end.toUTCString() );

If you need to get the UTC time from those, you can use UTC().

Getting Date with Start time of the Day

Use LocalDateTime to get current date and start of the day

val dateFormatter = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy HH:mm:ss")
val localDate = LocalDate.now() // your current date time
val startOfDay: LocalDateTime = localDate.atStartOfDay() // date time at start of the date
val timestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() // start time to timestamp
Log.d("Date:", "start date $timestamp")
Log.d("Date:", "start date parsed ${startOfDay.format(dateFormatter)}")

Output:

Start Date Timestamp : 1639506600000

Parsed TimeStamp: Wednesday, 15 December 2021 00:00:00

Edit : To get end of date time

val endOfDate: LocalDateTime = localDate.atTime(LocalTime.MAX)
val timestampEnd = endOfDate.atZone(ZoneId.of("UTC")).toInstant().epochSecond



Related Topics



Leave a reply



Submit