Programing

C #을 사용하여 시간 범위 값을 "hh : mm Am / Pm"형식으로 변환

lottogame 2020. 11. 3. 07:36
반응형

C #을 사용하여 시간 범위 값을 "hh : mm Am / Pm"형식으로 변환


System.TimeSpan다음과 같이 변수 유형에 저장된 값이 있습니다.

System.TimeSpan storedTime = 03:00:00;

String다음과 같이 다른 유형의 변수에 다시 저장할 수 있습니까 ?

String displayValue = "03:00 AM";

그리고 storedTime변수의 값이

storedTime = 16:00:00;

다음으로 변환해야합니다.

String displayValue = "04:00 PM";

날짜에 시간 범위를 추가하면됩니다.

TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"

문자열 형식을 사용하여 매우 간단합니다.

의 위에 .ToSTring("") :

  • "hh"를 사용하는 경우->> 01에서 12까지의 12 시간 시계를 사용하는 시간입니다.

  • "HH"를 사용하는 경우->> 00에서 23까지의 24 시간 시계를 사용하는 시간입니다.

  • "tt"를 추가하면->> Am / Pm 지정자.

23:12에서 11:12 Pm으로 변환하는 예 :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

다른 언어를 사용하는 Windows에서 실행되는 동일한 코드, 특히 다른 문화 언어를 사용하는 창에서 실행되는 동일한 코드가 동일한 코드로 다른 결과를 생성하기 때문에 다른 것에 대해 신경 쓸 필요가없는 것은 시스템 문화입니다.

아랍어 언어 문화로 설정된 창의 예는 다음과 같이 표시됩니다.

// 23:12 م

م는 저녁 (مساء의 첫 번째 문자)을 의미합니다.

다른 시스템 문화에서는 Windows 지역 및 언어 옵션에 설정된 내용에 따라 // 23:12 du가 표시됩니다.

Windows 제어판의 Windows 지역 및 언어-> 현재 형식 (콤보 박스)에서 다른 형식으로 변경할 수 있으며 변경 ... 적용하여 앱을 다시 빌드 (실행)하고 iam이 말하는 내용을 볼 수 있습니다.

그렇다면 현재 시스템의 문화가 영어로 설정되지 않은 경우 영어 이벤트에서 Am 및 Pm 단어를 강제로 표시 할 수 있습니까?

두 줄을 추가하는 것만으로 간단합니다 :->

첫 번째 단계 using System.Globalization;는 코드 위에 추가

이전 코드를 다음과 같이 수정합니다.

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => 기본 영어 형식 사용.

영어 (또는 다른 언어) 지역 형식으로 설정된 창을 사용하더라도 오후를 아랍어 또는 특정 언어로 만들고 싶습니다.

아랍어 예를위한 Soution :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

// 23:12 م가 표시됩니다.

내 시스템이 영어 지역 형식으로 설정된 경우 이벤트. 다른 언어 형식을 원하면 "ar-AE"를 변경할 수 있습니다. 각 언어 및 형식 목록이 있습니다.

예 : ar ar-SA 아랍어 ar-BH ar-BH 아랍어 (바레인) ar-DZ ar-DZ 아랍어 (알제리) ar-EG ar-EG 아랍어 (이집트)


예를 들어 TimeSpan를에 추가 할 수 있습니다 DateTime.

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

데모 : http://ideone.com/veJ6tT

04:00 PM

표준 날짜 및 시간 형식 문자열


string displayValue="03:00 AM";

이것은이다 시간에 지점 이 아닌 기간 (시간 범위).

따라서 기본 설계 또는 가정에 문제가 있습니다.

사용하려면 먼저 DateTime (특정 시점)으로 변환해야합니다. 원하는 문자열이되는 날짜 부분없이 DateTime의 형식을 지정할 수 있습니다.

TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1;               // any date will do
string result = d1.ToString("hh:mm:ss tt");

storeTime 변수는 다음과 같은 값을 가질 수 있습니다.
storeTime=16:00:00;

아니, 시간 범위 사이의 차이를 기록 할 수 없습니다, 그것은 4시의 값을 가질 수 있지만, 표현은 이진 16:004 pm.


여기에 기존 답변을 편승하여 수행합니다.

public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
    return new DateTime().Add(timeSpan).ToShortTimeString();
} 

public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
    return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}

당신은 당신의 DateTime개체를 TimeSpan가져와야하고 쉽게 서식을 지정할 수 있습니다.

한 가지 가능한 해결책은 시간 값이 0 인 날짜에 시간 범위를 추가하는 것입니다.

var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");

출력 값은 "03:00 AM"(영어 로케일의 경우)입니다.


You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.

TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.

As it says in the documentation;

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.

Also Microsoft Docs describes as follows;

A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.

So in this case, you can display using AM/PM as follows.

TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");


Side note :
Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents

a time interval that represents the fraction of the day that has elapsed since midnight.


Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.

TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");

str will be:

str = "04:00 PM"

You can try this:

   string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);

you can remove hh or mm or ss or tt according your need where hh is hour in 12 hr formate, mm is minutes,ss is seconds,and tt is AM/PM.


Parse timespan to DateTime. For Example.    
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
    public TimeSpan GetTimeSpanValue(string displayValue) 
        {   
            DateTime dateTime = DateTime.Now;
                if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
                          dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
                    else
                          dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
                    return dateTime.TimeOfDay;
                }

At first, you need to convert time span to DateTime structure:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Time format

var result = dt.ToString("t"); // Convert to string using Short Time format

참고URL : https://stackoverflow.com/questions/13044603/convert-time-span-value-to-format-hhmm-am-pm-using-c-sharp

반응형