Truncate NSDate (Zero-out time) - objective-c

I want to generate a new NSDate with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random NSDate.
Is there a way to achieve this? The documentation did not help me with this.
Example
Have: 2010-10-30 10:14:13 GMT
Want: 2010-10-30 00:00:00 GMT

unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
date is the date you want to remove the time from.
This separates the date and time and creates a new date with the default time (00:00:00).
EDIT
To take time zone into account:
NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];

Use NSCalendar's rangeOfUnit:startDate:interval:forDate:. This code will choose the day boundary based on the current time zone. If you want a particular time zone, you need to create an NSCalendar and set its time zone appropriately.
- (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit
{
NSDate *boundary;
[[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self];
return boundary;
}
- (NSDate*)dayBoundary
{
return [self boundaryForCalendarUnit:NSDayCalendarUnit];
}

With Swift 3, you can choose one of the four following patterns in order to solve your problem.
#1. Using Calendar startOfDay(for:)
startOfDay(for:) has the following declaration:
func startOfDay(for date: Date) -> Date
Returns the first moment of a given Date, as a Date.
The Playground code below shows how to use this method:
import Foundation
let date = Date()
// Get new date
let calendar = Calendar.current
let newDate = calendar.startOfDay(for: date)
// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate)
// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
#2. Using Calendar date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) has the following declaration:
func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
Returns a new Date representing the date calculated by setting hour, minute, and second to a given time on a specified Date.
The Playground code below shows how to use this method:
import Foundation
let date = Date()
// Get new date
let calendar = Calendar.current
let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date)
// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)
// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
#3. Using Calendar dateComponents(_:from:) and date(from:) methods
dateComponents(_:from:) has the following declaration:
func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents
Returns all the date components of a date, using the calendar time zone.
date(from:) has the following declaration:
func date(from components: DateComponents) -> Date?
Returns a date created from the specified components.
The Playground code below shows how to use those methods:
import Foundation
let date = Date()
// Get new date
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let newDate = calendar.date(from: components)
// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)
// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
#4. Using NSCalendar range(of:start:interval:for:)
range(of:start:interval:for:) has the following declaration:
func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool
Returns by reference the starting time and duration of a given calendar unit that contains a given date.
The Playground code below shows how to use this method:
import Foundation
let date = Date()
// Get new date
let calendar = Calendar.current as NSCalendar
var newDate: NSDate?
calendar.range(of: .day, start: &newDate, interval: nil, for: date)
// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate as! Date)
// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

I know its late, but there are now better methods:
why dont you just use
Swift 2
NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: yourDateToZeroOutTime, options: [])
Swift 5
var yourDate = Date() //Or any Date
yourDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: yourDate) ?? yourDate

Swift 3
extension Date {
func trimTime() -> Date {
var boundary = Date()
var interval: TimeInterval = 0
_ = Calendar.current.dateInterval(of: .day, start: &boundary, interval: &interval, for: self)
return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT()), since: boundary)
}
}

I would use the description method to get the given date as a string, then modify the string and create your new date with initWithString.
initWithString:
Returns an NSDate object initialized with a date and time value specified by a given string in the international string representation format.
(id)initWithString:(NSString *)description
Parameters
description
A string that specifies a date and time value in the international string representation format—YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM is a time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).
You must specify all fields of the format string, including the time zone offset, which must have a plus or minus sign prefix.
Return Value
An NSDate object initialized with a date and time value specified by aString.

Related

convert LocalDateTime to Date by using kotlin

I have a java.time.LocalDateTime and i want to convert it in java.util.Date
val myLocalDateTime = LocalDateTime.now().plusDays(5)
I want to convert LocalDateTime.now().plusDays(5) to java.util.Date in kotlin.
How Can i do it?
You need to add mandatory information in order to make a LocalDateTime convertable to a java.util.Date…
Before you try, think about if you can use Instant.now(), because the methods for legacy compatibility require Instants as arguments:
fun main() {
// get "now" as Instant
val now = Instant.now()
// print the java.util.Date created from the Instant
println(Date.from(now))
// use the Instant plus 5 days to create another date
val date = Date.from(now.plus(5, ChronoUnit.DAYS))
// create a formatter for the Date
val formatter = SimpleDateFormat("yyyy-MM-dd")
// and print it using the formatter
println(formatter.format(date))
}
Output (some moments ago on my middle-european machine):
Thu Feb 09 15:31:06 CET 2023
2023-02-14
If you really need to use a LocalDateTime, which has no zone or offset, you will have to add one, convert the result (a ZonedDateTime or an OffsetDateTime) toInstant() and create Dates from those…
If it's all about dates (year, month of year, day of month) without time of day, you could simply use a java.time.LocalDate:
fun main() {
// get "today" as LocalDate
val today = LocalDate.now()
// print it using toString() implicitly
println(today)
// add five days
val fiveDaysLater = today.plusDays(5)
// and print it formatted by a prebuilt formatter
println(fiveDaysLater.format(DateTimeFormatter.ISO_LOCAL_DATE))
}
Output:
2023-02-10
2023-02-15

Is there a way to customize the date formatter as per our requirements in swift iOS

I want to display a date in my viewcontroller as January 1-7,2005, which in-turn represents the dates of the current week like 1-7, 8-14.... But i am not finding how to customize the date formatter to have this format.
You can use the DateFormatter() function
let date = Date() // Gets current date
let dateFormatter = DateFormatter()
let monthInt = Calendar.current.component(.month, from: date) // Gets the current month number
let monthStr = Calendar.current.monthSymbols[monthInt-1] // Month to string
dateFormatter.dateFormat = "dd-M,YYYY"
let dateString = dateFormatter.string(from: date)
print("\(monthStr) \(dateString)")
Output: June 29-6,2020
Ensure your dateFormat conforms to ISO 8601 https://www.w3.org/TR/NOTE-datetime

Kotlin - How to get time ("HH:mm") from string Date

How can I get the time from a json where I have values like:
"time": ["1507457400000", "1507458600000"] //Strings
In Javascript I could do something like
new Date(1507457400000) // return Sun Oct 08 2017 12:10:00 GMT+0200
new Date(1507457400000).getHours() // return 12
new Date(1507457400000).getMinutes() // return 10
But I have no idea how to get the time using kotlin. Any idea what is the best way to get the time from the data I have?
val date = SimpleDateFormat("HH:mm").format(Date((1507457400000 / 1000)))
Use this:
val calendar = Calendar.getInstance()
calendar.timeInMillis = 1507457400000
val date = calendar.time
if you have the millisecond in a string like str:
val calendar = Calendar.getInstance()
calendar.timeInMillis = str.toLong()
val date = calendar.time
for hour and min:
val h = calendar.get(Calendar.HOUR_OF_DAY)
val m = calendar.get(Calendar.MINUTE)
val result = h.toString() + ":" + m.toString()

NSDateFormatter timeIntervalSince1970 strange behavior with milliseconds

I'm trying to parse a date with milliseconds using NSDateFormatter, and I'm getting weird results when I print out its time interval since 1970. Here's my test code:
var timeStr = "2015-09-29 14:32:42.297-07"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSx"
let date = dateFormatter.dateFromString(timeStr)!
let dateFormatted = String(format: "%.20f", date.timeIntervalSince1970)
print("date: \(dateFormatted)")
Result: "date: 1443562362.29699993133544921875\n"
Instead of ending with 297, it ends with something close to it. Why?
Seems this is just how doubles work. It's not related to NSDateFormatter. If I make a double with value 2.3 then print it to 20 decimal places, I get 2.99999990453636... or something.

How to set default time to 00:00:00 in kendo Date Time picker

Here is my Kendo datetime picker code
#(Html.Kendo().DateTimePicker()
.Name("start")
.Value(DateTime.Today)
.ParseFormats(new string[] { "MM/dd/yyyy" })
)
by this am getting 12/22/2014 12:00 AM but i want to diplay as 12/22/2014 00:00:00
how can i set default start date to the current day with the time set to 00:00:00
I tried like this but am not getting to display time as 00:00:00
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
$('#FromDate').data('kendoDateTimePicker').value(month, day, year);
$('#FromDate').data('kendoDateTimePicker').value(new Date("MM/dd/yyyy"));
Thanks for the help
I believe that is what you want: http://dojo.telerik.com/UBaQe ?
So in the C# ASP.MVC this code should work:
#(Html.Kendo().DateTimePicker()
.Name("start")
.Value(DateTime.Today)
.ParseFormats(new string[] { "MM/dd/yyyy" })
.Format("yyyy/MM/dd HH:mm:ss")
.TimeFormat("HH:mm:ss")
)