今日から特定の日付までの時間を計算するコードがいくつかあります。この日付は、ユーザーが日付ピッカーから選択した日付です。
以下にコードを投稿しますが、最初に私の問題です。選択した日付までの残りの月、日、時間などで更新されるラベルがあります。ただし、選択した日付の前日になると、おかしくなります。
私は(おそらく間違って)、真夜中までカウントダウンしたいと思っていたので、選択した日が来たらすぐに、ラベルを好きなものに変更します。代わりに、選択した日付の真夜中の約 4 時間前に、まだ 24 時間残っていると表示されます。
真夜中までカウントダウンしたいだけです。
systemCalendar = [NSCalendar currentCalendar];
unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
components = [systemCalendar components:unitFlags
fromDate:[NSDate date]
toDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"dateSaved"]
options:0];
if (![[NSUserDefaults standardUserDefaults] objectForKey:@"dateSaved"])
{
dateLbl.text = @"You haven't chosen a date yet.";
}
else
{
//Plural string variations
NSString *seconds = @"Seconds";
NSString *minutes = @"Minutes";
NSString *hours = @"Hours";
NSString *days = @"Days";
NSString *months = @"Months";
NSString *years = @"Years";
//No time left until wedding day
if ([components year] <= 0 && [components month] <= 0 && [components day] <= 0 && [components hour] <= 0 && [components minute] <= 0 && [components second] <= 0)
{
dateLbl.text = @"It's Your Day!";
}
//Hours left until day
else if ([components year] <= 0 && [components month] <= 0 && [components day] <= 0 && ([components hour] > 0 || [components minute] > 0 || [components second] > 0))
{
if ([components hour] > 1) hours = @"Hours";
else hours = @"Hour";
if ([components minute] > 1) minutes = @"Minutes";
else minutes = @"Minute";
if ([components second] > 1) seconds = @"Seconds";
else seconds = @"Second";
dateLbl.text = [NSString stringWithFormat:@"%i %@, %i %@, %i %@ Until Your Day", [components hour], hours, [components minute], minutes, [components second], seconds];
//dateLbl.text = @"Tomorrow is your day!";
}
//Days left until day
else if ([components year] <= 0 && [components month] <= 0 && [components day] > 0)
{
if ([components day] > 1) days = @"Days";
else days = @"Day";
dateLbl.text = [NSString stringWithFormat:@"%i %@ Until Your Day", [components day], days];
}
//Months left until day
else if ([components year] <= 0 && [components month] > 0)
{
if ([components month] > 1) months = @"Months";
else months = @"Month";
if ([components day] > 1) days = @"Days";
else days = @"Day";
dateLbl.text = [NSString stringWithFormat:@"%i %@, %i %@ Until Your Day", [components month], months, [components day], days];
}
//Years left until day
else if ([components year] > 0)
{
if ([components year] > 1) years = @"Years";
else years = @"Year";
if ([components month] > 1) months = @"Months";
else months = @"Month";
if ([components day] > 1) days = @"Days";
else days = @"Day";
dateLbl.text = [NSString stringWithFormat:@"%i %@, %i %@, %i %@ Until Your Day", [components year], years, [components month], months, [components day], days];
}
}