=================================
=================================
=================================
출처: http://blog.naver.com/PostView.nhn?blogId=goldrushing&logNo=130190777628
DateTime.Ticks 속성
이 인스턴스의 날짜와 시간을 나타내는 틱 수를 가져옵니다.
네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)
public long Ticks { get; } |
속성 값
형식: System.Int64
이 인스턴스의 날짜와 시간을 나타내는 틱 수입니다.
값은 DateTime.MinValue.Ticks와 DateTime.MaxValue.Ticks 사이입니다.
설명
1틱은 100나노초(천만분의 1초)를 나타냅니다.1밀리초는 10,000틱입니다. (1 밀리초 = 0.001 초)
이 속성의 값은 DateTime.MinValue를 나타내는 0001년 1월 1일 12:00:00 자정 이후 경과된 100나노초 간격의 수를 나타냅니다.
윤초로 인한 틱 수는 포함하지 않습니다.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleTimeSpanTicksTest { class Program { static void Main(string[] args) { DateTime centuryBegin = new DateTime(2014, 5, 8); DateTime currentDate = DateTime.Now; long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks; TimeSpan elapsedSpan = new TimeSpan(elapsedTicks); Console.WriteLine("Elapsed from the beginning of the century to {0:f}:", currentDate); Console.WriteLine(" {0:N0} nanoseconds", elapsedTicks * 100); Console.WriteLine(" {0:N0} ticks", elapsedTicks); Console.WriteLine(" {0:N2} seconds", elapsedSpan.TotalSeconds); Console.WriteLine(" {0:N2} minutes", elapsedSpan.TotalMinutes); Console.WriteLine(" {0:N0} days, {1} hours, {2} minutes, {3} seconds", elapsedSpan.Days, elapsedSpan.Hours, elapsedSpan.Minutes, elapsedSpan.Seconds); } } } |
실행결과는 다음과 같다.
두 날짜 사이의 간격을 Ticks로 구하고 이것을 nanoseconds, ticks, totalseconds, totalminutes, days, hours, minutes, seconds로 변환할 수 있다.
그럼 좋은하루 되세요.
[출처] C# : DateTime.Ticks 속성 , TimeSpan으로 시간간격 구하기|작성자 골드러쉬
=================================
=================================
=================================
출처: https://www.reddit.com/r/incremental_games/comments/3p89r2/need_help_with_systemdatetime_unity3d/
I just threw this together for you:
using UnityEngine;
using System.Collections;
using System;
public class OfflineTime : MonoBehaviour {
string debugMessage = "";
void Save() {
string dateTimeString = DateTime.UtcNow.ToString (System.Globalization.CultureInfo.InvariantCulture);
PlayerPrefs.SetString ("DateTime", dateTimeString);
debugMessage = string.Format ("Saved at {0}", dateTimeString);
}
void Load() {
DateTime dateTime;
bool didParse = System.DateTime.TryParse (PlayerPrefs.GetString ("DateTime"), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTime);
if (didParse) {
DateTime now = DateTime.UtcNow;
TimeSpan timeSpan = now - dateTime;
double secondsPassed = timeSpan.TotalSeconds;
debugMessage = string.Format ("{0} seconds have passed since the last save. Do something with secondsPassed and then resave.", secondsPassed);
} else {
debugMessage = "Either the DateTime was invalid or there wasn't a saved time.";
}
}
void OnGUI() {
if (GUILayout.Button ("Save")) {
Save ();
}
if (GUILayout.Button ("Load")) {
Load ();
}
GUILayout.Label (debugMessage);
}
}
=================================
=================================
=================================
출처: https://stackoverflow.com/questions/62151/datetime-now-vs-datetime-utcnow
This is a good question. I'm reviving it to give a little more detail on how .Net behaves with different Kind values. As @Jan Zich points out, It's actually a critically important property and is set differently depending on whether you use Now or UtcNow.
Internally the date is stored as Ticks which (contrary to @Carl Camera's answer) is different depending on if you use Now or UtcNow.
DateTime.UtcNow behaves like other languages. It sets Ticks to a GMT based value. It also sets Kind to Utc.
DateTime.Now alters the Ticks value to what it would be if it was your time of day in the GMT time zone. It also sets Kind to Local.
If you're 6 hours behind (GMT-6), you'll get the GMT time from 6 hours ago. .Net actually ignores Kind and treats this time as if it was 6 hours ago, even though it's supposed to be "now". This breaks even more if you create a DateTime instance then change your time zone and try to use it.
DateTime instances with different 'Kind' values are NOT compatible.
Let's look at some code...
DateTime utc = DateTime.UtcNow;
DateTime now = DateTime.Now;
Debug.Log (utc + " " + utc.Kind); // 05/20/2015 17:19:27 Utc
Debug.Log (now + " " + now.Kind); // 05/20/2015 10:19:27 Local
Debug.Log (utc.Ticks); // 635677391678617830
Debug.Log (now.Ticks); // 635677139678617840
now = now.AddHours(1);
TimeSpan diff = utc - now;
Debug.Log (diff); // 05:59:59.9999990
Debug.Log (utc < now); // false
Debug.Log (utc == now); // false
Debug.Log (utc > now); // true
Debug.Log (utc.ToUniversalTime() < now.ToUniversalTime()); // true
Debug.Log (utc.ToUniversalTime() == now.ToUniversalTime()); // false
Debug.Log (utc.ToUniversalTime() > now.ToUniversalTime()); // false
Debug.Log (utc.ToUniversalTime() - now.ToUniversalTime()); // -01:00:00.0000010
As you can see here, comparisons and math functions don't automatically convert to compatible times. The Timespan should have been almost one hour, but instead was almost 6. "utc < now" should have been true (I even added an hour to be sure), but was still false.
You can also see the 'work around' which is to simply convert to universal time anywhere that Kind is not the same.
My direct answer to the question agrees with the accepted answer's recommendation about when to use each one. You should always try to work with DateTime objects that have Kind=Utc, except during i/o (displaying and parsing). This means you should almost always be using DateTime.UtcNow, except for the cases where you're creating the object just to display it, and discard it right away.
=================================
=================================
=================================
일하다 짜놓은거
지정한 시점 (Add) 부터 몇초가 지났는지 (GetPassedSeconds) 알아내는 용도.
usingUnityEngine;
usingSystem.Collections;
publicstaticclass RegenTimer {
staticstring TIMER_KEY ="TIMER_";
publicstaticvoidAdd (string key)
{
string timerKeyStr = GetTimerKeyString(key);
string now = System.DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss");
PlayerPrefs.SetString(timerKeyStr, now);
PlayerPrefs.Save();
}
publicstaticvoidRemove (string key)
{
string timerKeyStr = GetTimerKeyString(key);
PlayerPrefs.DeleteKey(timerKeyStr);
PlayerPrefs.Save();
}
publicstaticintGetPassedSeconds (string key)
{
string timerKeyStr = GetTimerKeyString(key);
string startTimeStr = PlayerPrefs.GetString(timerKeyStr);
if(string.IsNullOrEmpty(startTimeStr) ==true) {
Add(key);
startTimeStr = PlayerPrefs.GetString(timerKeyStr);
}
System.DateTime start = System.DateTime.Parse(startTimeStr);
System.DateTime now = System.DateTime.UtcNow;
System.TimeSpan elapsedSpan =newSystem.TimeSpan(now.Ticks - start.Ticks);
return(int)elapsedSpan.TotalSeconds;
}
publicstaticvoidAddSeconds(string key,intsec)
{
string timerKeyStr = GetTimerKeyString(key);
string timeStr = PlayerPrefs.GetString(timerKeyStr);
System.DateTime date = System.DateTime.Parse(timeStr);
System.DateTime resultDate = date.AddSeconds(sec);
string resultStr = resultDate.ToString("yyyy/MM/dd HH:mm:ss");
PlayerPrefs.SetString(timerKeyStr, resultStr);
PlayerPrefs.Save();
}
publicstaticboolHasKey (string key)
{
string timerKeyStr = GetTimerKeyString(key);
string startTimeStr = PlayerPrefs.GetString(timerKeyStr);
return(string.IsNullOrEmpty(startTimeStr) ==false);
}
staticstring GetTimerKeyString (string key)
{
returnstring.Format("{0}{1}", TIMER\_KEY, key);
}
}
=================================
=================================
=================================
출처: https://pkmpkm1992.tistory.com/142
Local DateTime UTC 변환하기
Written by 김영일(Youngil Kim), C#.NET Developer
최근 다국어기반으로 솔루션개발을 하다보니까 시간정보를 현지에 맞게 설정해둘 필요가 있습니다. 이런 경우 UTC(Universal Time Coordinated / 협정 세계시)을 기준으로 타임존을 의식할 필요없이 정확한 현지 시간을 체크할 수 있습니다. 한국의 경우 +9:00입니다.
[UTCTimeCheck.cs]
using System;
using System.Collections.Generic;
using System.Text;
namespace UTCTimeCheck
{
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.UtcNow.AddHours(9);
Console.WriteLine(dt.ToString("yyyy/MM/dd hh:mm:ss"));
}
}
}
거꾸로 구하려면 -9한다.
DateTime dt = DateTime.UtcNow.AddHours(-9);
출처 : http://wingsbox.blogspot.kr/2013/03/local-datetime-utc.html
출처:https://pkmpkm1992.tistory.com/142[꼉로그]
=================================
=================================
=================================
출처: https://pkmpkm1992.tistory.com/143?category=1018647
System.DateTime StartDate = System.Convert.ToDateTime("2012/05/07 08:00"); // 시작시간 System.DateTime EndDate = System.Convert.ToDateTime("2012/05/10 10:20"); // 현재시간( 완료 시간 )
System.TimeSpan timeCal = EndDate - StartDate; // 시간차 계산
int timeCalDay = timeCal.Days;//날짜 차이
int timeCalHour = timeCal.Hours; //시간차이
int timeCalMinute = timeCal.Minutes;// 분 차이
Debug.Log(timeCalDay);
Debug.Log(timeCalHour);
Debug.Log(timeCalMinute);
System.DateTime time = System.DateTime.Now;
Debug.Log(time.ToString("hh:mm tt")); // 시간 / 분 / 오전오후
Debug.Log(time.ToString("MM/dd/yyyy")); // 월
출처 : http://cunity77.blogspot.kr/2016/01/blog-post_25.html
출처:https://pkmpkm1992.tistory.com/143?category=1018647[꼉로그]
=================================
=================================
=================================
'프로그래밍 관련 > 언어들의 코딩들 C++ JAVA C# 등..' 카테고리의 다른 글
[C#] struct 구조체 관련 (0) | 2019.04.07 |
---|---|
[Unity] 유니티 시간, 타임스캐줄러, 특정시간 호출 관련 (0) | 2019.04.06 |
[C#] 구조체, 기본변수형등등 에 null (Nullable<T> 타입) 사용하기 관련 (0) | 2019.04.01 |
[C#] c#에서 UnmanagedType의 종류 관련 (0) | 2019.04.01 |
[C#] private, public, protected, internal 접근자 설정 관련 (0) | 2019.03.27 |
댓글 영역