1

剣道のタイム ピッカーの値を 24 時間形式に保存する際に問題が発生しました。タイム ピッカーは"HH:mm tt"形式を示していますが、変換したいのですが"HH:mm:ss"、ドローダウン リストにタイム スパンを使用しています。

サンプルコード

String clientShiftId = formCollection["clientShiftId"];
            String clientId = formCollection["clientId"];
            String dateShift = formCollection["dllShiftDay"];
            String startTime = formCollection["txtStartTime"];
            String endTime = formCollection["txtEndTime"];
            var stayHere = formCollection["stayHere"];

            Client_Customer_Position_Shift clientCusPosShift = new Client_Customer_Position_Shift();
            try
            {

                if (String.IsNullOrWhiteSpace(clientShiftId) || clientShiftId == "0")
                {
                    client.Client_Customer_PositionID = Convert.ToInt32(clientId);
                    clientCusPosShift.Day_LookID = Convert.ToInt32(dateShift);
                    DateTime parsed = DateTime.ParseExact(endTime.Trim(), "hh:mm tt",CultureInfo.InvariantCulture);
                    client.EndTime = parsed.ToString("HH:mm:ss", CultureInfo.InvariantCulture);  <------- Line of Error 
DateTime parse = DateTime.ParseExact(startTime.Trim(), "hh:mm tt",CultureInfo.InvariantCulture);
                    client.StartTime = parse.ToString("HH:mm:ss", CultureInfo.InvariantCulture);  <------- Line of Error 
4

1 に答える 1

3

You can't parse it as a TimeSpan if it has an AM/PM designator. You could use:

DateTime parsed = DateTime.ParseExact(endTime.Trim(), "hh:mm tt",
                                      CultureInfo.InvariantCulture);

// If you need a string
client.EndTime = parsed.ToString("HH:mm:ss", CultureInfo.InvariantCulture);

// If you just need a TimeSpan
client.EndTime = parsed.TimeOfDay;

I'm assuming that the value you get will always be in the invariant culture? You should also consider using DateTime.TryParseExact instead of ParseExact, in order to detect invalid input more cleanly.

Note the "hh" instead of "HH" when parsing, by the way - you'll receive 11pm as "11:00 pm" rather than "23:00 pm". Also note how I'm using a local variable for the intermediate value - I would recommend that rather than repeatedly setting the same property (client.EndTime) which could lead to confusion when debugging.

(As an aside, you could also use my Noda Time library for this, which has a separate LocalTime type, which is more appropriate here as you don't have a date. I wouldn't suggest it for just this case, but if you're doing other date/time work in the app you may find it useful.)

于 2013-08-23T06:18:05.340 に答える