Related
I have date represented as integer like 20140820 and I want to parsing it as datetime, like 2014.08.20.
Do I need to parse each integer value (2014)(08)(02) using index or is there simpler way?
If your CurrentCulture supports yyyyMMdd format as a standard date and time format, you can just use DateTime.Parse method like;
int i = 20140820;
DateTime dt = DateTime.Parse(i.ToString());
If it doesn't support, you need to use DateTime.ParseExact or DateTime.TryParseExact methods to parse it as custom date and time format.
int i = 20140820;
DateTime dt;
if(DateTime.TryParseExact(i.ToString(), "yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Then you can format your DateTime with .ToString() method like;
string formattedDateTime = dt.ToString("yyyy.MM.dd", CultureInfo.InvariantCulture);
The easiest and most performance way would be something like:
int date = 20140820;
int d = date % 100;
int m = (date / 100) % 100;
int y = date / 10000;
var result = new DateTime(y, m, d);
Try This :-
string time = "20140820";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
OR
string str = "20140820";
string[] format = {"yyyyMMdd"};
DateTime date;
DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
now date variable will have required converted date of string '20140820'
int sampleDate = 20140820;
var dateFormat = DateTime.ParseExact(sampleDate.ToString(), "yyyyMMdd",
CultureInfo.InvariantCulture).ToString("yyyy.MM.dd");
result:
2014.08.20
So, we have two competing implementations,
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
int i = 20140820;
Console.WriteLine($"StringParse:{StringParse.Parse(i)}");
Console.WriteLine($"MathParse:{MathParse.Parse(i)}");
}
}
public static class StringParse
{
public static DateTime Parse(int i)
{
return DateTime.ParseExact(
i.ToString().AsSpan(),
"yyyyMMdd".AsSpan(),
CultureInfo.InvariantCulture);
}
}
public static class MathParse
{
public static DateTime Parse(int i)
{
return new DateTime(
Math.DivRem(Math.DivRem(i, 100, out var day), 100, out var month),
month,
day);
}
}
The string approach is probably safer and probably handles edge cases better.
Both will be fast and unlikely to be a performance bottle neck but it is my untested assertion that the math approach probably has better performance.
private static DateTime FromMS(long microSec)
{
long milliSec = (long)(microSec / 1000);
DateTime startTime = new DateTime(1970, 1, 1);
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime v = new DateTime(time.Ticks);
DateTime result = new DateTime(startTime.Year + v.Year, startTime.Month + v.Month, startTime.Day + v.Day, startTime.Hour + v.Hour, startTime.Minute + v.Minute, startTime.Millisecond + v.Millisecond);
return result;
}
This result is wrong...
Why ???
You already have the result of the conversion to milliseconds when you do:
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime v = new DateTime(time.Ticks); //This is the result
If you want to add the milliseconds to UNIX time, then all you have to do is:
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
result = result.Add(time);
If the time isn't in UTC then omit the DateTimeKind.Utc part, but it's generally a good idea to keep the time in UTC and only convert to local time when needed.
private static DateTime FromMS(long microSec)
{
long milliSec = (long)(microSec / 1000);
DateTime startTime = new DateTime(1970, 1, 1);
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
return startTime.Add(time);
}
I use this method to convert from a Unix Epoch (with milliseconds) to a DateTime object
private static readonly DateTime UnixEpochStart =
DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
public static DateTime ToDateTimeFromEpoch(this long epochTime)
{
DateTime result = UnixEpochStart.AddMilliseconds(epochTime);
return result;
}
long ticks = new DateTime(1970, 1, 1).Ticks;
DateTime dt = new DateTime(ticks);
dt.AddMilliseconds(milliSec);
Try this.
TimeSpan time = TimeSpan.FromMilliseconds(1509359657633);
DateTime date = new DateTime(1970, 1, 1).AddTicks(time.Ticks);
This will convert milliseconds into a correct DateTime.
NOTE:- If you get the milliseconds from JS like Date.now() the millisecond you received here is for UTC. So when you convert to C# DateTime, you will get DateTime in UTC time
In C# how can I convert Unix-style timestamp to yyyy-MM-ddThh:mm:ssZ?
Start by converting your milliseconds to a TimeSpan:
var time = TimeSpan.FromMilliseconds(milliseconds);
Now, in .NET 4 you can call .ToString() with a format string argument. See http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx
In previous versions of .NET, you'll have to manually construct the formatted string from the TimeSpan's properties.
new DateTime(numTicks * 10000)
The DateTime(long ticks) constructor is what you need. Each tick represents 100 nanoseconds so multiply by 10000 to get to 1 millisecond.
If the milliseconds is based on UNIX epoch time, then you can use:
var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
var time = posixTime.AddMilliseconds(milliSecs);
This worked for me:
DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
You can get just the DateTime from that if you need it.
Here you go:
public static class UnixDateTime
{
public static DateTimeOffset FromUnixTimeSeconds(long seconds)
{
if (seconds < -62135596800L || seconds > 253402300799L)
throw new ArgumentOutOfRangeException("seconds", seconds, "");
return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
{
if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)
throw new ArgumentOutOfRangeException("milliseconds", milliseconds, "");
return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);
}
public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)
{
return utcDateTime.Ticks / 10000000L - 62135596800L;
}
public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)
{
return utcDateTime.Ticks / 10000L - 62135596800000L;
}
[Test]
public void UnixSeconds()
{
DateTime utcNow = DateTime.UtcNow;
DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();
DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);
Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
}
[Test]
public void UnixMilliseconds()
{
DateTime utcNow = DateTime.UtcNow;
DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();
DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);
Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);
}
}
This sample will demonstrate the general idea, but you need to know if your starting date is DateTime.MinValue or something else:
int ms = 1000; // One second
var date = new DateTime(ms * 10000); // The constructor takes number of 100-nanoseconds ticks since DateTime.MinValue (midnight, january 1st, year 1)
string formatted = date.ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(formatted);
You can construct your datetime from ticks:
long ticks = new DateTime(1979, 07, 28, 22, 35, 5,
new CultureInfo("en-US", false).Calendar).Ticks;
DateTime dt3 = new DateTime(ticks);
Console.Write(dt3.ToString("yyyy-MM-ddThh:mm:ssZ"));
private static DateTime Milliseconds2Date(Double d)
{
TimeSpan time = TimeSpan.FromMilliseconds(d);
return new DateTime(1970, 1, 1) + time;
}
private static Double Date2Milliseconds(DateTime d)
{
var t = d.Subtract(new DateTime(1970, 1, 1));
return t.TotalMilliseconds;
}
This question should have the answer you need.
Short version:
DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");
i have code that takes a csharp datetime and converts it into a long to plot in the "flot" graph. here is the code
public static long GetJavascriptTimestamp(DateTime input)
{
TimeSpan span = new TimeSpan(DateTime.Parse("1/1/1970").Ticks);
DateTime time = input.Subtract(span);
return (long)(time.Ticks / 10000);
}
I now need an opposite function where i take this long value and get the csharp datetime object back. any idea if the above method can be reversed ?
DateTime date = new DateTime(1970, 1, 1).Add(new TimeSpan(yourLong * 10000));
Aren't you just looking for this?
public static DateTime DateTimeFromJavascript(long millisecs)
{
return new DateTime(1970, 1, 1).AddMilliseconds(millisecs);
}
Can be:
public static DateTime GetTimestampFromJS(long ts)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(ts*1000);
}
In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respectively. Currently I have the below code but was wondering if there was more of an elegant solution?
So for pdr = 20090521-20090523 would get "20090521 00:00:00" and "20090523 23:59:59"
private void ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
throw new Exception("Date period is of incorrect format");
}
if (dates[0].Length != 8 || dates[1].Length != 8)
{
throw new Exception("Split date periods are of incorrect format");
}
startDate = DateTime.ParseExact(dates[0] + " 00:00:00",
"yyyyMMdd HH:mm:ss", null);
endDate = DateTime.ParseExact(dates[1] + "23:59:59",
"yyyyMMdd HH::mm:ss", null);
}
I am surprised to see how an incorrect answer received so many upvotes:
The correct version would be as follows:
public static DateTime StartOfDay(this DateTime theDate)
{
return theDate.Date;
}
public static DateTime EndOfDay(this DateTime theDate)
{
return theDate.Date.AddDays(1).AddTicks(-1);
}
You could define two extension methods somewhere, in a utility class like so :
public static DateTime EndOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
}
public static DateTime StartOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
}
And then use them in code like so :
public DoSomething()
{
DateTime endOfThisDay = DateTime.Now.EndOfDay();
}
If you are only worried about .Net precision...
startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddTicks(-1).AddDays(1);
You really don't need to concatenate extra values onto the string for the time portion.
As an addendum, if you are using this for a query against, for example, a database...
startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddDays(1);
With a query of...
WHERE "startDate" >= #startDate AND "endDate" < #endDate
Then the precision issues noted in the comments won't really matter. The endDate in this case would not be part of the range, but the outside boundary.
The DateTime object has a property called Date which will return just the date portion. (The time portion is defaulted to 12:00 am).
I would recommend as a more elegant solution (IMHO) that if you want to allow any datetime on the last day, then you add 1 day to the date, and compare to allow times greater than or equal to the start date, but strictly less than the end date (plus 1 day).
// Calling code. beginDateTime and endDateTime are already set.
// beginDateTime and endDateTime are inclusive.
// targetDateTime is the date you want to check.
beginDateTime = beginDateTime.Date;
endDateTime = endDateTime.Date.AddDays(1);
if ( beginDateTime <= targetDateTime &&
targetDateTime < endDateTime )
// Do something.
public static class DateTimeExtension {
public static DateTime StartOfTheDay(this DateTime d) => new DateTime(d.Year, d.Month, d.Day, 0, 0,0);
public static DateTime EndOfTheDay(this DateTime d) => new DateTime(d.Year, d.Month, d.Day, 23, 59,59);
}
I use the following in C#
public static DateTime GetStartOfDay(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0);
}
public static DateTime GetEndOfDay(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59, 999);
}
Then in MS SQL I do the following:
if datepart(ms, #dateEnd) = 0
set #dateEnd = dateadd(ms, -3, #dateEnd)
This will result in MS SQL time of 23:59:59.997 which is the max time before becoming the next day.
You could simply use:
new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59, 999);
Which will work in MS SQL, but this is not as accurate in .Net side.
That's pretty much what I would do, with some small tweaks (really no big deal, just nitpicking):
The TryParse()/TryParseExact() methods should be used which return false instead of throwing exceptions.
FormatException is more specific than Exception
No need to check for Length == 8, because ParseExact()/TryParseExact() will do this
"00:00:00" and "23:59:59" are not needed
return true/false is you were able to parse, instead of throwing an exception (remember to check value returned from this method!)
Code:
private bool ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
return false;
}
// no need to check for Length == 8 because the following will do it anyway
// no need for "00:00:00" or "23:59:59" either, I prefer AddDays(1)
if(!DateTime.TryParseExact(dates[0], "yyyyMMdd", null, DateTimeStyles.None, out startDate))
return false;
if(!DateTime.TryParseExact(dates[1], "yyyyMMdd", null, DateTimeStyles.None, out endDate))
return false;
endDate = endDate.AddDays(1);
return true;
}
I think we're doing it wrong. There is no such thing as the end of the day. AddTick(-1) only works under the convention that there are no time intervals smaller than a tick. Which is implementation dependent. Admittedly the question comes with a reference implementation, namely the .Net Framework DateTime class, but still we should take this as a clue that the function we really want is not EndOfDay() but StartOfNextDay()
public static DateTime StartOfNextDay(this DateTime date)
{
return date.Date.AddDays(1);
}
The issue above regarding the few milliseconds can be resolved by querying the database with the next day's start date.
For example:
SELECT * FROM temp WHERE createdDate >= fromDate AND createdDate < toDate
Using the extension methods below you could set the from and to dates to:
DateTimeOffset fromDate = DateTimeOffset.UtcNow.StartOfDay();
DateTimeOffset toDate = DateTimeOffset.UtcNow.EndOfDay();
public static class DateExtentions
{
public static DateTimeOffset StartOfDay(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfDay(this DateTimeOffset dateTime)
{
return dateTime.StartOfDay().AddDays(1);
}
public static DateTimeOffset StartOfMonth(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, dateTime.Month, 1, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfMonth(this DateTimeOffset dateTime)
{
return dateTime.StartOfMonth().AddMonths(1);
}
public static DateTimeOffset StartOfYear(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, 1, 1, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfYear(this DateTimeOffset dateTime)
{
return dateTime.StartOfYear().AddYears(1);
}
}
For SQL Server (version 2008 R2 tested) this ranges works.
StarDate '2016-01-11 00:00:01.990'
EndDate '2016-01-19 23:59:59.990'
Seems like ticks is greater that the last second of day and automatically round to next day. So i test and works, i made a dummy table with two dates for check what values is sql server catching and inserting in the stored procedure those parameters.
In Java 8, you can do it using LocalDate as follows:
LocalDate localDateStart = LocalDate.now();
Date startDate = Date.from(localDateStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
LocalDate localDateEnd = localDateStart.plusDays(1);
Date endDate = Date.from(localDateEnd.atStartOfDay(ZoneId.systemDefault()).toInstant());