The following code crashes and burns and I don't understand why:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172");
Console.Write(dt.AddSeconds(d));
Can someone tell me what's going on? I just can't seem to be able to figure out why...
EDIT
This value comes back from the Salesforce REST API and from what I understand it's a Unix epoch time stamp. "The time of token issue, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970)."
SOLUTION
Salesforce REST API is in fact sending milliseconds back for the issued_at field when performing the OAuth request when they say they're sending seconds...
As others have said, the problem is that the value is too large.
Having looked over it, I believe it represents milliseconds since the Unix epoch, not seconds so you want:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172"); // Or avoid parsing if possible :)
Console.Write(dt.AddMilliseconds(d));
Either that, or divide by 1000 before calling AddSeconds - but obviously that will lose data.
The value you are adding results in a date outside of the valid range of dates that a DateTime supports.
DateTime supports 01/01/0001 00:00:00 to 31/12/9999 23:59:59.
A simple calculation of 1332958778172/3600/24/365 gives 42267 years.
I think the double value is genuinely too large. It represents just over 42,267 years (if my maths is correct), and DateTime.MaxValue is 23:59:59.9999999, December 31, 9999
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
Console.Write(dt.AddSeconds(1332958778172D));
Except that...
1332958778172/60/60/24/365 = 42,267 years... which DateTime can only go up to 23:59:59.9999999, December 31, 9999
I had a similar issue where I was required to add a configurable timespan to a datetime.
If the configuration is not correct I have to assume the 'worst scenario' : MaxValue.
I solved it by implementing an extension to DateTime (still in test phase) :
/// <summary>
/// Removes a timespan from a date, returning MinValue or MaxValue instead of throwing exception when if the resulting date
/// is behind the Min/Max values
/// </summary>
/// <returns></returns>
public static DateTime SafeAdd(this DateTime source, TimeSpan value)
{
// Add or remove ?
if (value.Ticks > 0)
{
// add
var maxTicksToAdd = DateTime.MaxValue - source;
if (value.Ticks > maxTicksToAdd.Ticks)
return DateTime.MaxValue;
}
else
{
var maxTicksToRemove = source - DateTime.MinValue;
// get the value to remove in unsigned representation.
// negating MinValues is impossible because it would result in a value bigger than MaxValue : (-32768 .. 0 .. 32767)
var absValue = value == TimeSpan.MinValue ? TimeSpan.MaxValue : -value;
if (absValue.Ticks > maxTicksToRemove.Ticks)
return DateTime.MinValue;
}
return source + value;
}
Looks like this timestamp is in milliseconds, try below code it should work fine.
DateTime nDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
double epoch = 1585008000000;
DateTime rDate = nDateTime.AddMilliseconds(epoch);
In my case I had to consume an api object as a double and convert the unix time to a DateTime:
DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Double.Parse("1596225600000"));
Related
I have a number that is the number of seconds since January 1st 1970. It was created with this:
var utcNow = (int) Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Now need to convert that number to a date in string form like this:
Tue, Jan 15, 2019
Can someone give me some suggestions on how I can do this. I think I can format it myself but I need a suggestion on how to convert the integer utcNow into a datetime first.
static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
DateTime time = epoch.AddSeconds(utcNow);
You can also use this in reverse:
var seconds = (time - epoch).TotalSeconds;
(which gives a double, but you can cast it to int or long etc)
Some answer are already given, and work. But this is, I believe, the most elegant way of doing it. I'm using DateTimeOffset.FromUnixTimeSeconds(int64)
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(utcNow);
And now you can convert it into a DateTime Struct with help of this blog entry
Substract the given time from current time and it gives timespan instance, from that you can get total seconds
var fromDate = new DateTime(1970,1 ,1);
var diffrance = DateTime.UtcNow.Subtract(fromDate);
Console.WriteLine(diffrance.TotalSeconds);
I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to the system, however, does not offer that precision, so I need to simply drop the milliseconds.
I feel like I'm missing something obvious, but I haven't found an elegant way to do it (C#).
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...
var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
Here is an extension method based on a previous answer that will let you truncate to any resolution...
Usage:
DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)
Class:
public static class DateTimeUtils
{
/// <summary>
/// <para>Truncates a DateTime to a specified resolution.</para>
/// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
/// </summary>
/// <param name="date">The DateTime object to truncate</param>
/// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
/// <returns>Truncated DateTime</returns>
public static DateTime Truncate(this DateTime date, long resolution)
{
return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
}
}
DateTime d = DateTime.Now;
d = d.AddMilliseconds(-d.Millisecond);
Sometimes you want to truncate to something calendar-based, like year or month. Here's an extension method that lets you choose any resolution.
public enum DateTimeResolution
{
Year, Month, Day, Hour, Minute, Second, Millisecond, Tick
}
public static DateTime Truncate(this DateTime self, DateTimeResolution resolution = DateTimeResolution.Second)
{
switch (resolution)
{
case DateTimeResolution.Year:
return new DateTime(self.Year, 1, 1, 0, 0, 0, 0, self.Kind);
case DateTimeResolution.Month:
return new DateTime(self.Year, self.Month, 1, 0, 0, 0, self.Kind);
case DateTimeResolution.Day:
return new DateTime(self.Year, self.Month, self.Day, 0, 0, 0, self.Kind);
case DateTimeResolution.Hour:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerHour));
case DateTimeResolution.Minute:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMinute));
case DateTimeResolution.Second:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerSecond));
case DateTimeResolution.Millisecond:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMillisecond));
case DateTimeResolution.Tick:
return self.AddTicks(0);
default:
throw new ArgumentException("unrecognized resolution", "resolution");
}
}
Instead of dropping the milliseconds then comparing, why not compare the difference?
DateTime x; DateTime y;
bool areEqual = (x-y).TotalSeconds == 0;
or
TimeSpan precision = TimeSpan.FromSeconds(1);
bool areEqual = (x-y).Duration() < precision;
To round down to the second:
dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerSecond)
Replace with TicksPerMinute to round down to the minute.
If your code is performance sensitive, be cautious about
new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second)
My app was spending 12% of CPU time in System.DateTime.GetDatePart.
Less obvious but more than 2 times faster :
// 10000000 runs
DateTime d = DateTime.Now;
// 484,375ms
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
// 1296,875ms
d = d.AddMilliseconds(-d.Millisecond);
Not the fastest solution but simple and easy to understand:
DateTime d = DateTime.Now;
d = d.Date.AddHours(d.Hour).AddMinutes(d.Minute).AddSeconds(d.Second)
A way for easy reading is...
//Remove milliseconds
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", null);
And more...
//Remove seconds
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH:mm"), "yyyy-MM-dd HH:mm", null);
//Remove minutes
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH"), "yyyy-MM-dd HH", null);
//and go on...
I understand that it is easy to understand, but it lacks performance.
Regarding Diadistis response. This worked for me, except I had to use Floor to remove the fractional part of the division before the multiplication. So,
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
becomes
d = new DateTime(Math.Floor(d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
I would have expected the division of two Long values to result in a Long, thus removing the decimal part, but it resolves it as a Double leaving the exact same value after the multiplication.
Eppsy
2 Extension methods for the solutions mentioned above
public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate > compareDate;
}
public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate >= compareDate;
}
usage:
bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);
This is my version of the extension methods posted here and in similar questions. This validates the ticks value in an easy to read way and preserves the DateTimeKind of the original DateTime instance. (This has subtle but relevant side effects when storing to a database like MongoDB.)
If the true goal is to truncate a DateTime to a specified value (i.e. Hours/Minutes/Seconds/MS) I recommend implementing this extension method in your code instead. It ensures that you can only truncate to a valid precision and it preserves the important DateTimeKind metadata of your original instance:
public static DateTime Truncate(this DateTime dateTime, long ticks)
{
bool isValid = ticks == TimeSpan.TicksPerDay
|| ticks == TimeSpan.TicksPerHour
|| ticks == TimeSpan.TicksPerMinute
|| ticks == TimeSpan.TicksPerSecond
|| ticks == TimeSpan.TicksPerMillisecond;
// https://stackoverflow.com/questions/21704604/have-datetime-now-return-to-the-nearest-second
return isValid
? DateTime.SpecifyKind(
new DateTime(
dateTime.Ticks - (dateTime.Ticks % ticks)
),
dateTime.Kind
)
: throw new ArgumentException("Invalid ticks value given. Only TimeSpan tick values are allowed.");
}
Then you can use the method like this:
DateTime dateTime = DateTime.UtcNow.Truncate(TimeSpan.TicksPerMillisecond);
dateTime.Kind => DateTimeKind.Utc
DateID.Text = DateTime.Today.ToShortDateString();
Use ToShortDateString() //Date 2-02-2016
Use ToShortDateString() // Time
And By Use Of
ToLongDateString() // its show 19 February 2016.
:P
New Method
String Date = DateTime.Today.ToString("dd-MMM-yyyy");
// define String pass parameter dd-mmm-yyyy return 24-feb-2016
Or shown on textbox
txtDate.Text = DateTime.Today.ToString("dd-MMM-yyyy");
// put on PageonLoad
In my case, I was aiming to save TimeSpan from datetimePicker tool without saving the seconds and the milliseconds, and here is the solution.
First convert the datetimePicker.value to your desired format, which mine is "HH:mm" then convert it back to TimeSpan.
var datetime = datetimepicker1.Value.ToString("HH:mm");
TimeSpan timeSpan = Convert.ToDateTime(datetime).TimeOfDay;
You can simply use Split
new TimeSpan(new DateTime(1970, 1, 1).Ticks).TotalSeconds.ToString().Split('.')[0]
I know the answer is quite late, but the best way to get rid of milliseconds is
var currentDateTime = DateTime.Now.ToString("s");
Try printing the value of the variable, it will show the date time, without milliseconds.
I'm working with the GroupWise 2014 Rest API and I have a problem parsing their date format.
When you fetch a user you receive a json object with "timeCreated": 1419951016000,
But I can't figure out what format that date is.
I've tried
DateTime.Parse
DateTime.FromFileTime
DateTime.FromFileTimeUtc
The value 1419951016000 should be around the time 2014-12-30 15:50
Looks like unix time in milliseconds since January 1st, 1970 at UTC. Current unix time in seconds is shown here as 1419964283.
To convert to a DateTime to unix time, see here: How to convert UNIX timestamp to DateTime and vice versa?. That code works for unix time in seconds; the following works for unix time in milliseconds, represented as a long:
public static class UnixTimeHelper
{
const long MillisecondsToTicks = 10000;
static readonly DateTime utcEpochStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
static DateTime UtcEpochStart { get { return utcEpochStart; }}
public static DateTime ToDateTime(long unixTimeInMs, DateTimeKind kind)
{
var dateTime = UtcEpochStart + new TimeSpan(MillisecondsToTicks * unixTimeInMs);
if (kind == DateTimeKind.Local)
dateTime = dateTime.ToLocalTime();
return dateTime;
}
public static long ToUnixTimeInMs(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local)
dateTime = dateTime.ToUniversalTime();
var span = dateTime - UtcEpochStart;
return (long)(span.Ticks / MillisecondsToTicks);
}
}
With this code. UnixTimeHelper.ToDateTime(1419951016000, DateTimeKind.Utc).ToString() gives the value "12/30/2014 2:50:16 PM". Is your desired value of "2014-12-30 15:50" in UTC or your local time?
If you are using Json.NET to serialize your JSON, you can write a custom JsonConverter to do the conversion automatically from a DateTime property using the instructions here: Writing a custom Json.NET DateTime Converter . That code also works for unix time in seconds and so will need to be tweaked.
(Finally, seconding Plutonix's suggestion to double-check the documentation. In particular you need to read what the documentation says about the time zone in which the times are returned. It's probably UTC but it pays to make sure.)
Update
After a quick search the online doc looks pretty bad, but this page makes mention of
expiretime
long
Optional. Use an explicit expiration cut-off time. The time is specified as a java long time.
java.util.Date represents "the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT" as a long.
I'm scraping a website and in the html it has a date in the following format:
"date":"\/Date(1184050800000-0700)\/"
If this was in javascript, it would be a date object and I could use its methods to retrieve the data in whatever format I like. However, I'm scraping it in a C# app. Does anyone know what this format is? Is it the total number of seconds after a certain date or something? I need a way to convert this to a C# datetime object.
If I'm not mistaken, that is a Unix timestamp in milliseconds. 1184050800000 is the timestamp itself, and -0700 is the time zone. This epoch convertor confirms.
Here is some code I've used before for converting Unix timestamps into DateTimes. Be sure to include only the part before -0700:
/// <summary>
/// Converts a Unix timestamp into a System.DateTime
/// </summary>
/// <param name="timestamp">The Unix timestamp in milliseconds to convert, as a double</param>
/// <returns>DateTime obtained through conversion</returns>
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp / 1000); // convert from milliseconds to seconds
}
If you encounter Unix timestamps that are in seconds, you just have to remove the / 1000 part of the last line of the code.
As sinelaw says it seems to be a regex of some sort, however I tried parsing out the numeric values:
1184050800000-0700
And they seem to correspond to:
1184050800000 - Unix timestamp in milliseconds
-0700 - this would be the timezone offset UTC-07:00
You could parse it (I assume it's a string from a JSON object) and convert it to a DateTime like this:
string dateString = "/Date(1184050800000-0700)/";
Regex re = new Regex(#"(\d+)([-+]\d{4})");
Match match = re.Match(dateString);
long timestamp = Convert.ToInt64(match.Groups[1].Value);
int offset = Convert.ToInt32(match.Groups[2].Value) / 100;
DateTime date = new DateTime(1970, 1, 1).AddMilliseconds(timestamp).AddHours(-offset);
Console.WriteLine(date); // 7/10/2007 2:00:00 PM
Am I wrong? It looks like a regexp to me, not a date object at all.
DateTime now = new DateTime(1184050800000);
Console.WriteLine(now); // 2/01/0001 8:53:25 AM
Could this be correct if you aren't interested in the year?
I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to the system, however, does not offer that precision, so I need to simply drop the milliseconds.
I feel like I'm missing something obvious, but I haven't found an elegant way to do it (C#).
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...
var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
Here is an extension method based on a previous answer that will let you truncate to any resolution...
Usage:
DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)
Class:
public static class DateTimeUtils
{
/// <summary>
/// <para>Truncates a DateTime to a specified resolution.</para>
/// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
/// </summary>
/// <param name="date">The DateTime object to truncate</param>
/// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
/// <returns>Truncated DateTime</returns>
public static DateTime Truncate(this DateTime date, long resolution)
{
return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
}
}
DateTime d = DateTime.Now;
d = d.AddMilliseconds(-d.Millisecond);
Sometimes you want to truncate to something calendar-based, like year or month. Here's an extension method that lets you choose any resolution.
public enum DateTimeResolution
{
Year, Month, Day, Hour, Minute, Second, Millisecond, Tick
}
public static DateTime Truncate(this DateTime self, DateTimeResolution resolution = DateTimeResolution.Second)
{
switch (resolution)
{
case DateTimeResolution.Year:
return new DateTime(self.Year, 1, 1, 0, 0, 0, 0, self.Kind);
case DateTimeResolution.Month:
return new DateTime(self.Year, self.Month, 1, 0, 0, 0, self.Kind);
case DateTimeResolution.Day:
return new DateTime(self.Year, self.Month, self.Day, 0, 0, 0, self.Kind);
case DateTimeResolution.Hour:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerHour));
case DateTimeResolution.Minute:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMinute));
case DateTimeResolution.Second:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerSecond));
case DateTimeResolution.Millisecond:
return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMillisecond));
case DateTimeResolution.Tick:
return self.AddTicks(0);
default:
throw new ArgumentException("unrecognized resolution", "resolution");
}
}
Instead of dropping the milliseconds then comparing, why not compare the difference?
DateTime x; DateTime y;
bool areEqual = (x-y).TotalSeconds == 0;
or
TimeSpan precision = TimeSpan.FromSeconds(1);
bool areEqual = (x-y).Duration() < precision;
To round down to the second:
dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerSecond)
Replace with TicksPerMinute to round down to the minute.
If your code is performance sensitive, be cautious about
new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second)
My app was spending 12% of CPU time in System.DateTime.GetDatePart.
Less obvious but more than 2 times faster :
// 10000000 runs
DateTime d = DateTime.Now;
// 484,375ms
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
// 1296,875ms
d = d.AddMilliseconds(-d.Millisecond);
Not the fastest solution but simple and easy to understand:
DateTime d = DateTime.Now;
d = d.Date.AddHours(d.Hour).AddMinutes(d.Minute).AddSeconds(d.Second)
A way for easy reading is...
//Remove milliseconds
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", null);
And more...
//Remove seconds
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH:mm"), "yyyy-MM-dd HH:mm", null);
//Remove minutes
DateTime date = DateTime.Now;
date = DateTime.ParseExact(date.ToString("yyyy-MM-dd HH"), "yyyy-MM-dd HH", null);
//and go on...
I understand that it is easy to understand, but it lacks performance.
Regarding Diadistis response. This worked for me, except I had to use Floor to remove the fractional part of the division before the multiplication. So,
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
becomes
d = new DateTime(Math.Floor(d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
I would have expected the division of two Long values to result in a Long, thus removing the decimal part, but it resolves it as a Double leaving the exact same value after the multiplication.
Eppsy
2 Extension methods for the solutions mentioned above
public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate > compareDate;
}
public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate >= compareDate;
}
usage:
bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);
This is my version of the extension methods posted here and in similar questions. This validates the ticks value in an easy to read way and preserves the DateTimeKind of the original DateTime instance. (This has subtle but relevant side effects when storing to a database like MongoDB.)
If the true goal is to truncate a DateTime to a specified value (i.e. Hours/Minutes/Seconds/MS) I recommend implementing this extension method in your code instead. It ensures that you can only truncate to a valid precision and it preserves the important DateTimeKind metadata of your original instance:
public static DateTime Truncate(this DateTime dateTime, long ticks)
{
bool isValid = ticks == TimeSpan.TicksPerDay
|| ticks == TimeSpan.TicksPerHour
|| ticks == TimeSpan.TicksPerMinute
|| ticks == TimeSpan.TicksPerSecond
|| ticks == TimeSpan.TicksPerMillisecond;
// https://stackoverflow.com/questions/21704604/have-datetime-now-return-to-the-nearest-second
return isValid
? DateTime.SpecifyKind(
new DateTime(
dateTime.Ticks - (dateTime.Ticks % ticks)
),
dateTime.Kind
)
: throw new ArgumentException("Invalid ticks value given. Only TimeSpan tick values are allowed.");
}
Then you can use the method like this:
DateTime dateTime = DateTime.UtcNow.Truncate(TimeSpan.TicksPerMillisecond);
dateTime.Kind => DateTimeKind.Utc
DateID.Text = DateTime.Today.ToShortDateString();
Use ToShortDateString() //Date 2-02-2016
Use ToShortDateString() // Time
And By Use Of
ToLongDateString() // its show 19 February 2016.
:P
New Method
String Date = DateTime.Today.ToString("dd-MMM-yyyy");
// define String pass parameter dd-mmm-yyyy return 24-feb-2016
Or shown on textbox
txtDate.Text = DateTime.Today.ToString("dd-MMM-yyyy");
// put on PageonLoad
In my case, I was aiming to save TimeSpan from datetimePicker tool without saving the seconds and the milliseconds, and here is the solution.
First convert the datetimePicker.value to your desired format, which mine is "HH:mm" then convert it back to TimeSpan.
var datetime = datetimepicker1.Value.ToString("HH:mm");
TimeSpan timeSpan = Convert.ToDateTime(datetime).TimeOfDay;
You can simply use Split
new TimeSpan(new DateTime(1970, 1, 1).Ticks).TotalSeconds.ToString().Split('.')[0]
I know the answer is quite late, but the best way to get rid of milliseconds is
var currentDateTime = DateTime.Now.ToString("s");
Try printing the value of the variable, it will show the date time, without milliseconds.