AnonProgrammer
AnonProgrammer

Reputation: 239

Remove leading zero with date formatter

If 24hr format, if date has no minutes, there shouldn't be any zeros padding.

example where time == 3:00pm:

dateFormatter.dateFormat = @"H:m" 

result: 15:0

expected: 15

Upvotes: 0

Views: 449

Answers (2)

Craig Pickering
Craig Pickering

Reputation: 1184

The DateComponentsFormatter has a property zeroFormattingBehavior to achieve this sort of thing.

When the value for a particular unit is 0, the zero formatting behavior determines whether that value is retained or omitted from any resulting strings. For example, when the formatting behavior is dropTrailing, the value of one hour, ten minutes, and zero seconds would omit the mention of seconds.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318814

There is no built in support to get something like 15:30 for 3:30pm and just 15 for 3:00pm. That would be pretty non-standard.

If you really want such behavior, use H:mm for your format. Then remove any trailing :00 from the result.

Upvotes: 1

Related Questions