블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2737)
Unity3D (817)
Programming (474)
Python (8)
TinyXML (5)
STL (13)
D3D (3)
MFC (1)
C/C++ (54)
C++/CLI (45)
C# (250)
WinForm (6)
WPF (5)
Math (10)
A.I. (1)
Win32API (11)
Algorithm (3)
Design Pattern (7)
UML (1)
MaxScript (1)
FMOD (4)
FX Studio (1)
Lua (2)
Terrain (1)
Shader (3)
boost (2)
Xml (2)
JSON (4)
Etc (11)
Monad (1)
Html5 (4)
Qt (1)
Houdini (0)
Regex (10)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-24 00:01

c# 서버시간 가져오기 (8)

나는 날짜와 시간을 사용하여 얻을 수있다 :

DateTime now = DateTime.Now;

DateTime 형식 자체로 현재 날짜와 시간을 따로 따로 가져올 수 있습니까?

ASP.net ( C# )에서 DateTime picker 대화 상자를 사용하지 않습니다.


 

음, Today 속성을 사용하여 Today DateTime  DateTime 으로 가져올 수 있습니다.

DateTime today = DateTime.Today;

또는 더 일반적으로 Date 속성을 사용할 수 있습니다. 예를 들어, UTC 날짜를 원할 경우 다음을 사용할 수 있습니다.

DateTime dateTime = DateTime.UtcNow.Date;

그게 당신이 필요로하는 것이 든 없는지는 분명하지 않습니다 ... 단지 날짜를 인쇄 하기를 원하면 다음을 사용할 수 있습니다 :

Console.WriteLine(dateTime.ToString("d"));

또는 명시 적 형식을 사용하십시오.

Console.WriteLine(dateTime.ToString("dd/MM/yyyy"));

standard  custom 날짜 / 시간 형식 문자열에 대해 자세히 알아보십시오. 상황에 따라 문화를 지정하고 싶을 수도 있습니다.

시간과 별도로 날짜에 대해 이야기 할 수있는보다 표현력있는 날짜 / 시간 API를 원한다면, 시작한 Noda Time 프로젝트를 살펴볼 수 있습니다. 아직 제작 준비가되지 않았지만, 우리는 당신이 그걸로하고 싶은 것을 듣고 싶습니다 ...


 

현재 시간 :

DateTime.Now.ToString("HH:mm:ss");

현재 날짜 :

DateTime.Today.ToString("dd-MM-yyyy");


 

Today 속성을 사용하십시오. DateTime.Now 날짜 구성 요소를 반환합니다. DateTime.Now.Date 와 같습니다.


 

여기에서 형식 문자열을 전달하여 날짜 만 가져올 수 있습니다. 현재 날짜에 대한 요구 사항에 따라 다른 날짜 형식을 사용할 수 있습니다.

DateTime.Now.ToString("M/d/yyyy");

결과 : '2010 년 9 월 1 일 '

DateTime.Now.ToString("M-d-yyyy");

결과 : '9-1-2015'

DateTime.Now.ToString("yyyy-MM-dd");

결과 : "2015-09-01"

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

결과 : "2015-09-01 09:20:10"

자세한 내용 custom


 

용도

txtdate.Text = DateTime.Today.ToString("dd-MM-yyyy");


 

for month DateTime.Now.ToString("MM"); for Date DateTime.Now.ToString("dd"); for year DateTime.Now.ToString("yyyy");


 

string now = Convert.ToString(DateTime.Now.ToShortDateString()); Console.WriteLine(now); Console.ReadLine();


 

.NET에는 내장 된 날짜 전용 유형이 없습니다.

규칙은 자정으로 설정된 시간 부분과 함께 DateTime 을 사용하는 것입니다.

정적 Today 속성은 오늘 날짜를 알려줍니다.

 

[출처] https://code-examples.net/ko/q/6805f2

 

어제날짜 현재 날짜 만 C#으로 가져 오기

나는 날짜와 시간을 사용하여 얻을 수있다:DateTime now=DateTime.Now; DateTime 형식 자체로 현재 날짜와 시간을 따로 따로 가져올 수 있습니까? ASP.net(C#)에서 DateTime picker 대화 상자를 사용하지 않습니다.

code-examples.net

 

반응형
Posted by blueasa
, |
반응형
Posted by blueasa
, |

(http://link2me.tistory.com 에서 발췌)

기타 : split를 string문자열로 자를때 word_1.Split(new string[] {"\\"}, StringSplitOptions.None) C# Split함수의 경우 직접 문자열을 구분자로 줄수 없다.

Split 은 기본적으로 문자를 입력 받도록 되어 있다. 문자열을 char[]형식으로 변경 후 사용 가능하다.

 

string str = "서울시/서초구/양재동";
string[] result = str.Split(new char[] { '/' });  // /   열 result  라.
for (int i = 0; i < result.Length ; i++)  // 은 0  며,   
{
    MessageBox.Show(i + "번째 배열 ==> " + result[i]);
}

 

string str = "jsk005@naver.com";
char[] sp ="@".ToCharArray();
string[] result = str.Split(sp);
for (int i = 0; i < result.Length; i++)
{
    MessageBox.Show(i + "번째 배열 ==> " + result[i]);
}

 

string str = "홍 길 동";
string[] result = str.Split(new char[] {' '});  // new char[] {}  도 공백으로 나눈다는 의미
for (int i = 0; i < result.Length; i++)
{
    MessageBox.Show(i + "번째 배열 ==> " + result[i]);
}

 

위의 예제와 아래 예제의 차이점을 보면 split  자(char)  열(string)이다. 

string 으로 할 경우에는 반드시 StringSplitOptions.None 또는 StringSplitOptions.RemoveEmptyEntries 까지 추가해줘야만 에러가 발생하지 않는다. 물론 위의 것도 StringSplitOptions 를 추가해줘도 된다.

 

string str = "홍길동~~~이순신~~~강감찬~~~을지문덕";
string[] result = str.Split(new string[] {"~~~"}, StringSplitOptions.None);
for (int i = 0; i < result.Length; i++)
{
    MessageBox.Show(i + "번째 배열 ==> " + result[i]);
}

string[] separator = new string[1] { "\r\n\r\n" };  //분리할 기준 문자열
string[] strResult = s.Split(separator, StringSplitOptions.RemoveEmptyEntries);

  

* StringSplitOptions.None  //     

* StringSplitOptions.RemoveEmptyEntries  // 반환값에 빈 부분 문자열 포함 안됨

 

foreach (string strValue in strResult)
{
    
}

또는 

for (var i =0 ; i < strResult.Length ; i++) 

{

}

 

//구     

string str = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result = str.Split(stringSeparators, StringSplitOptions.None);

for (int i = 0; i < result.Length; i++)
{
    if (String.IsNullOrEmpty(result[i]))  //  null  
    {
        MessageBox.Show("null" + result[i]);
    }
    else
    {
        MessageBox.Show(i + "번째 배열 ==> " + result[i]);
    }                
} 

 

아래와 같이StringSplitOptions.RemoveEmptyEntries 으로 수정하면 결과가 어떻게 나올까?

string str = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result = str.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);  

// 반환값에 빈 부분 문자열 포함 안됨
for (int i = 0; i < result.Length; i++)
{
    if (String.IsNullOrEmpty(result[i]))
    {
        MessageBox.Show("null" + result[i]);
    }
    else
    {
        MessageBox.Show(i + "번째 배열 ==> " + result[i]);
    }                
} 

결과는 null 이나 공백은 무시되므로 배열은 0, 1, 2 만 추출된다.



   

System.Text.RegularExpressions.Regex.Split(자를 문자열, 정규식 문자열)

using System;
using System.Text.RegularExpressions;

 

string str = "cat\r\ndog\r\nanimal\r\nperson";
string[] result = Regex.Split(str, "\r\n");
for (int i = 0; i < result.Length; i++)
{
    MessageBox.Show(i + "번째 배열 ==> " + result[i]);
} 



포함된 문자열의 개수 구하기
int
 count = source.Split('/').Length - 1;

 

[출처] http://hunq.blogspot.com/2016/09/c-split.html

반응형
Posted by blueasa
, |

[Link] https://github.com/Yortw/Yort.Ntp

반응형
Posted by blueasa
, |


[링크] https://xtasy.tistory.com/665

반응형
Posted by blueasa
, |


[링크] http://codingcoding.tistory.com/382


반응형
Posted by blueasa
, |

.NET> 4.0에서는 다음을 사용할 수 있습니다.

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

또는 날짜 형식을 원할 경우이 작업을 수행 할 수도 있습니다.

TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = date.ToString("hh:mm:tt");

더 많은 정보는 Custom TimeSpan Format Strings를 확인하십시오.

 Question

초를 (Hour : Minutes : Seconds : Milliseconds) 시간으로 변환하는 가장 좋은 방법은 무엇입니까?

내가 80 초를 가지고 있다고 가정 해 봅시다. .NET에서 80 초를 DateTime이나 그와 비슷한 형식 (00h : 00m : 00s : 00ms)으로 변환 할 수있는 특수화 된 클래스 / 기술이 있습니까?







private string ConvertTime(double miliSeconds)
{
    var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
    // Converts the total miliseconds to the human readable time format
    return timeSpan.ToString(@"hh\:mm\:ss\:fff");
}

//테스트

    [TestCase(1002, "00:00:01:002")]
    [TestCase(700011, "00:11:40:011")]
    [TestCase(113879834, "07:37:59:834")]
    public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
    {
        // Arrange
        var obj = new Class();;

        // Act
        var resultMessage = obj.ConvertTime(totalMiliSeconds);

        // Assert
        Assert.AreEqual(expectedMessage, resultMessage);
    }



VB.NET에서는 C #과 동일합니다.

Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20



가장 빠른 방법을 알기 위해 몇 가지 벤치 마크를 수행했으며 이는 내 결과 및 결론입니다. 각 방법을 10M 번 실행하고 실행 당 평균 시간을 주석을 추가했습니다.

입력 된 밀리 초가 1 일로 제한되지 않으면 (결과는 143 : 59 : 59.999  수 있음) 다음과 같은 옵션이 있습니다.

// 0.86 ms
static string Method1(int millisecs)
{
    int hours = millisecs / 3600000;
    int mins = (millisecs % 3600000) / 60000;
    // Make sure you use the appropriate decimal separator
    return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}", hours, mins, millisecs % 60000 / 1000, millisecs % 1000);
}

// 0.89 ms
static string Method2(int millisecs)
{
    double s = millisecs % 60000 / 1000.0;
    millisecs /= 60000;
    int mins = millisecs % 60;
    int hours = millisecs / 60;
    return string.Format("{0:D2}:{1:D2}:{2:00.000}", hours, mins, s);
}

// 0.95 ms
static string Method3(int millisecs)
{
    TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
    // Make sure you use the appropriate decimal separator
    return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
        (int)t.TotalHours,
        t.Minutes,
        t.Seconds,
        t.Milliseconds);
}

입력 된 밀리 초가 1 일로 제한되는 경우 (결과가 23 : 59 : 59.999보다 클 수 없습니다) 이러한 옵션은 더 빠르거나 느릴 때까지 있습니다.

// 0.58 ms
static string Method5(int millisecs)
{
    // Fastest way to create a DateTime at midnight
    // Make sure you use the appropriate decimal separator
    return DateTime.FromBinary(599266080000000000).AddMilliseconds(millisecs).ToString("HH:mm:ss.fff");
}

// 0.59 ms
static string Method4(int millisecs)
{
    // Make sure you use the appropriate decimal separator
    return TimeSpan.FromMilliseconds(millisecs).ToString(@"hh\:mm\:ss\.fff");
}

// 0.93 ms
static string Method6(int millisecs)
{
    TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
    // Make sure you use the appropriate decimal separator
    return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
        t.Hours,
        t.Minutes,
        t.Seconds,
        t.Milliseconds);
}

입력이 불과 몇 초일 경우, 메소드가 약간 더 빠릅니다. 다시 말하지만, 입력 초가 1 일로 제한되지 않으면 결과가 143 : 59 : 59  수 있습니다.

// 0.63 ms
static string Method1(int secs)
{
    int hours = secs / 3600;
    int mins = (secs % 3600) / 60;
    secs = secs % 60;
    return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}

// 0.64 ms
static string Method2(int secs)
{
    int s = secs % 60;
    secs /= 60;
    int mins = secs % 60;
    int hours = secs / 60;
    return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, s);
}

// 0.70 ms
static string Method3(int secs)
{
    TimeSpan t = TimeSpan.FromSeconds(secs);
    return string.Format("{0:D2}:{1:D2}:{2:D2}",
        (int)t.TotalHours,
        t.Minutes,
        t.Seconds);
}

그리고 입력 한 초가 1 일로 제한되는 경우 (결과는 결코 23:59:59보다 클 수 없습니다) :

// 0.33 ms
static string Method5(int secs)
{
    // Fastest way to create a DateTime at midnight
    return DateTime.FromBinary(599266080000000000).AddSeconds(secs).ToString("HH:mm:ss");
}

// 0.34 ms
static string Method4(int secs)
{
    return TimeSpan.FromSeconds(secs).ToString(@"hh\:mm\:ss");
}

// 0.70 ms
static string Method6(int secs)
{
    TimeSpan t = TimeSpan.FromSeconds(secs);
    return string.Format("{0:D2}:{1:D2}:{2:D2}",
        t.Hours,
        t.Minutes,
        t.Seconds);
}

마지막 의견으로, string.Format 가 00 대신 D2 를 사용하면 조금 더 빠르다는 것을 알았습니다.


[출처] https://code.i-harness.com/ko/q/7131a

반응형
Posted by blueasa
, |


[링크] https://github.com/JanKallman/EPPlus


반응형
Posted by blueasa
, |

[주의] 레지스트리를 수정하는 내용이니 주의해서 사용하세요.



C# 으로 OleDB를 이용해서 Excel을 읽어 들이고, Sqlite(.db)로 변환하는 Converter를 만들어서 사용하는 데


긴 문자열을 넣었더니 잘려서 컨버팅 되길래 확인해보니 255 글자 제한이 걸려 있다.


검색해서 확인해보니 여러가지 해결 방법들이 포스팅 돼 있는데 조금씩 안맞아서 확인해보고 정리해서 올려 놓는다.



[레지스트리 수정으로 255 글자 제한 풀기]


아래 버전 및 OS bit에 맞는 레지스트리를 찾아가서 TypeGuessRows 값을 0으로 바꾸면 된다.

(참고: 개발에 사용된 Excel 버전임. 윈도우 설치된 엑셀 버전이 아님)

(기본 값은 8인데, DataSet을 만들 때 기본으로 설정 된 윗 8줄에 있는 가장 큰 글자수를 DataType 길이로 잡는다고 한다.

 기본 글자 제한은 255자이고, 0으로 바꾸면 전체를 검사해서 DataType 길이로 잡는다고 함.)


[주의] 성능상의 이유로 글자수를 제한(Default:8) 하는 거라고 하니 감안해서 사용할 사람만 하기를..


  [Windowns 32bit]

Excel 2000, 2003 (xls)

  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel

  (Excel 97 = 3.5)


- Excel 2013 (xlsx)

  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\15.0\Access Connectivity Engine\Engines\Excel

  (2016 = 16.0, 2013 = 15.0, 2010 = 14.0, 2007 = 12.0)


  [Windowns 64bit]

Excel 2000, 2003 (xls)

  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Jet\4.0\Engines\Excel

  (Excel 97 = 3.5)


- Excel 2013 (xlsx)

  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Office\15.0\Access Connectivity Engine\Engines\Excel

 (2016 = 16.0, 2013 = 15.0, 2010 = 14.0, 2007 = 12.0)



[레지스트리 파일 다운로드]

Fix_255_Char_32bit_Excel_2000_2003.reg

Fix_255_Char_32bit_Excel_2007.reg

Fix_255_Char_32bit_Excel_2010.reg

Fix_255_Char_32bit_Excel_2013.reg


Fix_255_Char_64bit_Excel_2000_2003.reg

Fix_255_Char_64bit_Excel_2007.reg

Fix_255_Char_64bit_Excel_2010.reg

Fix_255_Char_64bit_Excel_2013.reg



    [Excel 데이터 수정으로 255 글자 제한 풀기] (확인 안해봤음)


- 위에도 적었지만 DataSet을 만들 때 기본으로 설정 된 윗 8줄에 있는 가장 큰 글자수를 DataType 길이로 잡는다고 한다.

  8줄 이내에 255 글자 이상의 사용하지 않는 Dummy 데이터를 넣으면 해결 된다고 함. 




[참조] http://www.todal.net/241?category=367351

[참조] http://it-developer.tistory.com/427

[참조] http://lemondory.tistory.com/129

[참조] http://ariswear.tistory.com/37

반응형
Posted by blueasa
, |
  1.  
  2.         Dictionary<string, string> dict = new Dictionary<string, string>()
  3.         {
  4.             { "A""String A" },
  5.             { "B""String B" },
  6.             { "C""String C" },
  7.         };
  8.         string[] keys = new string[dict.Keys.Count];
  9.         dict.Keys.CopyTo(keys0);
  10.         for (int i = 0; i < keys.Length++i)
  11.         {
  12.             Debug.Log(dict[keys [i]]);
  13.         }
  14.  


[출처] https://forum.unity.com/threads/c-dictionary-loop.337804/

반응형
Posted by blueasa
, |