Format for more than 24 hours

964 views Asked by At

In my database i store time that people have to spend on a task in minutes. For example 600 minutes. When I create this task I want the user to fill in Hours follow by minutes for example: 30:20 or 30 or 1:20. In order to do this i did the following

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan AllocatedTime { get; set; }

public int AllocatedMinutes { get; set; }

When the user enters his information in the field he uses allocatedtime, which is later converted to minutes in the Controller.

The problem is though, whenever the entered time is more than 23:59 it will give an error that it's in the wrong format. I've tried to several things to solve this but it didn't work out, does anyone know how to solve this problem?

2

There are 2 answers

8
xxbbcc On

This is not an answer to your question but a suggestion for a different approach. I think your attempt to get duration in the form of hh:mm would be confusing to users (I would raise an eyebrow if I saw 327:15 - this is not a natural way to read time. It's also cumbersome when you talk about more than a day or two.

I'd suggest to use a different duration format; something like Xd Yh Zm where X, Y and Z are days, hours and minutes, respectively. Each part could be optional, but this would make it a lot easier for users to enter the timespan in question, since they'd be entering natural time units.

You could then use a regular expression to try to get the various parts and build an actual TimeSpan out of the values.

This regex could be a start:

(?:(?<days>\d+)d\s)?\s*(?:(?<hours>\d+)h\s)?\s*(?:(?<minutes>\d+)m)?

Note: I only tested this for a few minutes so it may not cover all the possibilities but it should be a good enough start.

2
vincent de g On

After trying and trying... i finnally figured it out :

[RegularExpression(@"^[0-9][0-9]?[0-9]?(:[0-5][0-9])?$", ErrorMessage = "wrong")]