DateTime group by date or hours - c#

01.02.2010 0:00:00 -> 01.02.2010 anytime
01.02.2010 0:00:00 -> 01.02.2010 0:any minutes and seconds
so here is my date :
DateTime x;
it's
01.02.2010 0:00:00
as a string
x.Date.ToString()
here I compare date
DatarowsForOneDay = dt.Select("DailyRecTime= '" + x.ToString() + "'");
So how can I group by date + Hours without care about minutes and seconds.

You could write your own IEqualityComparer<DateTime> to only compare the parts of the DateTime you care about. LINQ's GroupBy has an overload that takes an IEqualityComparer. I had the same problem recently and did just that.
But you would have to call GroupBy before converting to strings. If you can't then you might want to create an IEqualityComparer<string> and parse the strings back to DateTime before comparing.
I don't have the original code with me right now. I re-typed this from memory and did not test it.
public class DateAndHourComparer : IEqualityComparer
{
public bool Equals(DateTime x, DateTime y)
{
var xAsDateAndHours = AsDateHoursAndMinutes(x);
var yAsDateAndHours = AsDateHoursAndMinutes(y);
return xAsDateAndHours.Equals(yAsDateAndHours);
}
private DateTime AsDateHoursAndMinutes(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month,
dateTime.Day, dateTime.Hour,
dateTime.Minute, 0);
}
public int GetHashCode(DateTime obj)
{
return AsDateHoursAndMinutes(obj).GetHashCode();
}
}
I never did the string based version, but it could use the above DateTime based code and look something like...
public class DateAndHourStringComparer : IEqualityComparer
{
private readonly DateAndHourComparer dateComparer = new DateAndHourComparer();
public bool Equals(string x, string y)
{
var xDate = DateTime.Parse(x);
var yDate = DateTime.Parse(y);
return dateComparer.Equals(xDate, yDate);
}
public int GetHashCode(string obj)
{
var date = DateTime.Parse(obj);
return dateComparer.GetHashCode(date);
}
}
I have not tested it, I did not add null checks or format checks. The code is meant to demonstrate the general idea.

You can pass a parameter with DateTime.ToString(string pattern).
More information # http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm.

Related

Merge duplicate data with condition in a List

I have a List of Members:
List<Members> MyMembers= new List<Members>();
Members class:
public class Members
{
public int IdKey;
public string name;
public string relationBegin;
public string relationEnd;
public bool isOriginal;
}
I need to merge duplicate IdKey into one.
This can be done using something like:
MyMembers=MyMembers.GroupBy(x => x.IdKey )
.Select(g => new Members{ IdKey = g.Key })
.ToList();
Here is where the fun begins.
The condiation is that if we detect duplicate IdKey It need to preserve the one that has isOriginal=true (if both isOriginal=false, we leave isOriginal to false but update dates begin and end as explained in next statment)
Furthermore,
We need preserve the lowest relationBegin and highest relationEnd from the two duplicates, Sometimes relationBegin or relationEnd could be Null or empty.
Example:
Row1:
IsOriginal=true
relationBegin = 1/1/2017
relationEnd = 10/10/2018
Example:
Row2:
IsOriginal=false
relationBegin = 1/1/2015
relationEnd = NULL
Result would be:
IsOriginal= true
relationBegin=1/1/2015
relationEnd 10/10/2018
It would be better if your Member class would have DateTime instead of string Date time.
if you need them in string, you can have property like below.
public class Members
{
public int IdKey;
public string name;
public string relationBegin;
public string relationEnd;
public bool isOriginal;
public DateTime RelationBeginDate
{
get { return DateTime.ParseExact(relationBegin, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture); }
}
public DateTime RelationEndDate
{
get { return DateTime.ParseExact(relationEnd, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture); }
}
public Members(int IdKey, string name, string relationBegin, string relationEnd, bool isOriginal)
{
//assign paramters to proper properties
}
}
and your desired linq will be something like below.
MyMembers = MyMembers.GroupBy(x => x.IdKey)
.Select(g => new Members(
g.Key, //Id will be same as you shown in question
g.FirstOrDefault().name, //assuming name will be same in all
g.Select(x => x.RelationBeginDate).Min().ToString("dd-MM-yyyy hh:mm:ss"), //Min begin date
g.Select(x => x.RelationEndDate).Max().ToString("dd-MM-yyyy hh:mm:ss"), //Max end date
g.Any( x => x.isOriginal))).ToList(); //if isOriginal = true found

I Want Convert My Datetime to TimeStamp C#?

I want to convert my datetime in C# (e.g. 2009-06-22 16:35:16.000) to something like this 1196550000000. I tried the following method but it fails.
public static double GetTimestamp(DateTime value)
{
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse(value.ToString()).Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
Int64 timestamp = ticks;
return timestamp;
}
First of all, you don't need to ToString() and Reparse the DateTime. If you want just the Date you can use the DateTime.Date property.
Then, this should be simple enough (using DateTime.Now as a reference point):
public static double GetTimestamp(DateTime value)
{
return new TimeSpan(DateTime.UtcNow.Ticks - value.Ticks).TotalSeconds;
}
In case the parsing you did in your question did refer to extracting the date from the DateTime, you can use the following:
public static double GetTimestamp(DateTime value)
{
return new TimeSpan(DateTime.UtcNow.Ticks - value.Date.Ticks).TotalSeconds;
}
EDIT : You appear to want some kind of posix time conversion which can be achieved like this :
private static readonly DateTime POSIXRoot = new DateTime(1970, 1, 1, 0, 0, 0, 0);
public static double GetPosixSeconds(DateTime value)
{
return (value - POSIXRoot).TotalSeconds;
}
public static DateTime GetDateTime(double posixSeconds) {
return POSIXRoot.AddSeconds(posixSeconds);
}

DateTime? AddDays Extension Method

I want to write an extension method that adds one day to a Nullable DateTime, but modifies the date itself.
I want to use it as follows:
someDate.AddOneDay();
This directly changes the value of someDate.
The code I initially wrote was:
public static DateTime? AddOneDay(this DateTime? date)
{
if (date.HasValue)
{
date.Value = date.Value.AddDays(1);
}
return null;
}
but this doesn't work since the reference is changed thus calling it this way
won't change the value of someDate.
Is there a way to achieve this and avoid code like:
someDate = someDate.AddOneDay();
Also I was thinking for some setter of the DateTime properties, but they don't have any..
public int Day { get; }
public int Month { get; }
public int Year { get; }
You can't DateTime is immutable, and should stay that way.
Just do:
someDate = someDate.AddOneDay();
And if you want to be more specific, you could rename your function to:
DateTime? someDate = someDate.AddOneDayOrDefault();
old school %)
public static void AddOneDay(ref DateTime date)
{
if (date != null) date = date.AddDays(1);
}
usage:
DateTime date = DateTime.Now;
AddOneDay(ref date);
UPD
one line version of method:
public static void AddOneDay(ref DateTime date) { date = date.AddDays(1); }
C# does support a similar feature, even for mutable values, which is the use of += on nullable values:
DateTime? date = GetDate();
var oneDay = TimeSpan.FromDays(1);
date += oneDay;

Send variables to other classes

Can I have a function that checks if true or false and send my verbal to other classes?
I tried:
public class Func
{
public static bool CheckDate(string number)
{
string new_number = number.ToString();
if (new_number.Length==8)
{
string yyyy = new_number.Substring(0, 4);
string mm = new_number.Substring(4, 2);
string dd = new_number.Substring(6, 2);
return true;
}
else
{
return false;
}
}
}
I want to send the verbal yyyy, mm, dd to my Program.cs class.
What should I do?
Don't reinvent wheels, use the DateTime.TryParseExact method which is built specifically for this purpose. Forget about regexes and substrings when you are dealing with dates in the .NET framework:
public static bool CheckDate(string number, out DateTime date)
{
return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
And now as you can see defining the CheckDate becomes kinda meaningless because it already exists in the BCL. You would simply use it like this:
string number = "that's your number coming from somewhere which should be a date";
DateTime date;
if (DateTime.TryParseExact(
number,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date
))
{
// the number was in the correct format
// => you could use the days, months, from the date variable which is now a DateTime
string dd = date.Day.ToString();
string mm = date.Month.ToString();
string yyyy = date.Year.ToString();
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}
UPDATE:
Since I got a remark in the comments section that I am not actually answering the question, you could use a similar approach to the one I recommend. But please, promise me you will never write a code like this, it's just for illustration of the TryXXX pattern.
define a model:
public class Patterns
{
public string DD { get; set; }
public string MM { get; set; }
public string YYYY { get; set; }
}
and then modify your CheckDate method so that it sends an out parameter:
public static bool CheckDate(string number, out Patterns patterns)
{
patterns = null;
string new_number = number.ToString();
if (new_number.Length == 8)
{
Patterns = new Patterns
{
YYYY = new_number.Substring(0, 4),
MM = new_number.Substring(4, 2),
DD = new_number.Substring(6, 2)
}
return true;
}
else
{
return false;
}
}
which you could use like this:
string number = "that's your number coming from somewhere which should be a date";
Patterns patterns;
if (CheckDate(numbers, out patterns)
{
string dd = patterns.DD;
string mm = patterns.MM;
string yyyy = patterns.YYYY;
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}
The CheckDate function’s aim is to check if a date is valid. Don’t introduce crappy side effects: write another function that actually sends your stuff to the object you want.
If you want to check if a string is a date, do it in CheckDate.
When you know a string is a date, extract the date elements you want from it through such a ExtractDateElem function, but please, no side-effects.
you have to declare your variables as below...
public static string yyyy;
public static string mm ;
public static string dd ;
Or
protected static string yyyy;
protected static string mm ;
protected static string dd ;
as per your need and depends where your program.cs file is...

How to remove time portion of date in C# in DateTime object only?

I need to remove time portion of date time or probably have the date in following format in object form not in the form of string.
06/26/2009 00:00:00:000
I can not use any string conversion methods as I need the date in object form.
I tried first converting the DateTime to a string, remove the time specific date from it, but it adds 12:00:00 AM as soon as I convert it back to DateTime object back again.
Use the Date property:
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;
The date variable will contain the date, the time part will be 00:00:00.
You can use format strings to give the output string the format you like.
DateTime dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
Read more about Custom date and time format strings.
Use the method ToShortDateString. See the documentation http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
var dateTimeNow = DateTime.Now; // Return 00/00/0000 00:00:00
var dateOnlyString = dateTimeNow.ToShortDateString(); //Return 00/00/0000
Have a look at the DateTime.Date property.
Gets the date component of this instance.
The Date property will return the date at midnight.
One option could be to get the individual values (day/month/year) separately and store it in the type you want.
var dateAndTime = DateTime.Now;
int year = dateAndTime.Year;
int month = dateAndTime.Month;
int day = dateAndTime.Day;
string.Format("{0}/{1}/{2}", month, day, year);
None of the above answers solved my problem on winforms.
the easiest way to reach ONLY date is the simple function in Datetime:
DateTime dt = DateTime.now;
String BirthDate = dt.ToShortDateString();
You will only have date in Birthday string .
Try to make your own Structure for that. DateTime object will have date and time both
You can't. A DateTime in .NET always have a time, defaulting to 00:00:00:000. The Date property of a DateTime is also a DateTime (!), thus having a time defaulting to 00:00:00:000 as well.
This is a shortage in the .NET Framework, and it could be argued that DateTime in .NET violates the Single Responsibility Principle.
The easiest way is something like this and it will return only the date:
var date = DateTime.Now.ToShortDateString();
Here is another method using String.Format
DateTime todaysDate = DateTime.UtcNow;
string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);
Console.WriteLine("Date with Time: "+ todaysDate.ToString());
Console.WriteLine("Date Only : " + dateString);
Output:
Date with Time: 9/4/2016 11:42:16 AM
Date Only : 04/09/2016
This also works if the Date Time is stored in database.
For More Date and Time formatting check these links:
Reference 1
Reference 2
Hope helps.
DateTime.Date
var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime
This way of get only date without time
DateTime date = DateTime.Now;
string Strdateonly = date.ToString("d");
Output = 5/16/2015
Use date.ToShortDateString() to get the date without the time component
var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019
use date.ToString() to customize the format of the date
var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019
Since .NET 6 / C# 10 you can do this:
var dateOnly = DateOnly.FromDateTime(dateTime);
I wrote a DateOnly structure. This uses a DateTime under the skin but no time parts are exposed publically:
using System;
public struct DateOnly : IComparable, IFormattable, IComparable<DateOnly>, IEquatable<DateOnly>
{
private DateTime _dateValue;
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
DateOnly otherDateOnly = (DateOnly)obj;
if (otherDateOnly != null)
{
return ToDateTime().CompareTo(otherDateOnly.ToDateTime());
}
else
{
throw new ArgumentException("Object is not a DateOnly");
}
}
int IComparable<DateOnly>.CompareTo(DateOnly other)
{
return this.CompareToOfT(other);
}
public int CompareToOfT(DateOnly other)
{
// If other is not a valid object reference, this instance is greater.
if (other == new DateOnly())
{
return 1;
}
return this.ToDateTime().CompareTo(other.ToDateTime());
}
bool IEquatable<DateOnly>.Equals(DateOnly other)
{
return this.EqualsOfT(other);
}
public bool EqualsOfT(DateOnly other)
{
if (other == new DateOnly())
{
return false;
}
if (this.Year == other.Year && this.Month == other.Month && this.Day == other.Day)
{
return true;
}
else
{
return false;
}
}
public static DateOnly Now()
{
return new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
public static bool TryParse(string s, ref DateOnly result)
{
DateTime dateValue = default(DateTime);
if (DateTime.TryParse(s, out dateValue))
{
result = new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
return true;
}
else
{
return false;
}
}
public static DateOnly Parse(string s)
{
DateTime dateValue = default(DateTime);
dateValue = DateTime.Parse(s);
return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
}
public static DateOnly ParseExact(string s, string format)
{
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue = default(DateTime);
dateValue = DateTime.ParseExact(s, format, provider);
return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
}
public DateOnly(int yearValue, int monthValue, int dayValue) : this()
{
Year = yearValue;
Month = monthValue;
Day = dayValue;
}
public DateOnly AddDays(double value)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddDays(value);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DateOnly AddMonths(int months)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddMonths(months);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DateOnly AddYears(int years)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddYears(years);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DayOfWeek DayOfWeek
{
get
{
return _dateValue.DayOfWeek;
}
}
public DateTime ToDateTime()
{
return _dateValue;
}
public int Year
{
get
{
return _dateValue.Year;
}
set
{
_dateValue = new DateTime(value, Month, Day);
}
}
public int Month
{
get
{
return _dateValue.Month;
}
set
{
_dateValue = new DateTime(Year, value, Day);
}
}
public int Day
{
get
{
return _dateValue.Day;
}
set
{
_dateValue = new DateTime(Year, Month, value);
}
}
public static bool operator == (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() == aDateOnly2.ToDateTime());
}
public static bool operator != (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() != aDateOnly2.ToDateTime());
}
public static bool operator > (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() > aDateOnly2.ToDateTime());
}
public static bool operator < (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() < aDateOnly2.ToDateTime());
}
public static bool operator >= (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() >= aDateOnly2.ToDateTime());
}
public static bool operator <= (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() <= aDateOnly2.ToDateTime());
}
public static TimeSpan operator - (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() - aDateOnly2.ToDateTime());
}
public override string ToString()
{
return _dateValue.ToShortDateString();
}
public string ToString(string format)
{
return _dateValue.ToString(format);
}
public string ToString(string fmt, IFormatProvider provider)
{
return string.Format("{0:" + fmt + "}", _dateValue);
}
public string ToShortDateString()
{
return _dateValue.ToShortDateString();
}
public string ToDbFormat()
{
return string.Format("{0:yyyy-MM-dd}", _dateValue);
}
}
This is converted from VB.NET, so apologies if some conversions are not 100%
I'm surprised no one has mentioned DateTime.Today
var date = DateTime.Today;
// {7/1/2014 12:00:00 AM}
See MSDN
If you are converting it to string, you can easily do it like this.
I'm taking date as your DateTime object.
date.ToString("d");
This will give you only the date.
You Can Try This for the Only Date From the Datetime
String.Format("{0:d/M/YYYY}",dt);
Where dt is the DateTime
Came across this post when trying to solve the original Q.
I am using Asp.Net and after some research I have found when you are binding to the value of the date in code behind, you can drop the time so it will not display on screen.
C#:
DateTime Today = DateTime.Now;
aspx:
<%: this.Today.ToShortDateString() %>
use
DateTime.Now.ToString("dd-MM-yyyy");
I know this is an old post with many answers, but I haven't seen this way of removing the time portion. Suppose you have a DateTime variable called myDate, with the date with time part. You can create a new DateTime object from it, without the time part, using this constructor:
public DateTime(int year, int month, int day);
Like this:
myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
This way you create a new DateTime object based on the old one, with 00:00:00 as time part.
You can use this simple code below.
Code: DateTime.Now.ToShortDateString();
Ex.
Console.WriteLine(DateTime.Now.ToShortDateString());
This is for C#10 and above where now a DateOnly and TimeOnly format is available. Using below format, you can extract DateOnly from a DateTime format.
DateOnly myDateNoTime = DateOnly.FromDateTime(DateTime.Now);
string dt = myCalender.SelectedDate.ToString();
string date = dt.Remove(10);
displayDate.Content = date;
If you take date from calender, with this we also get time. Which is not required all time. Using this we can remove time from date.
in my experience none of the said solutions worked, maybe because I wanted to remove the time from extracted date from database, but the code below worked fine:
var date = target_date.Value.ToString("dd/MM/yyyy");
Declare the variable as a string.
example :
public string dateOfBirth ;
then assign a value like :
dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();
This could be simply done this way:
var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
Create a struct that holds only the properties you want. Then an extension method to easily get that struct from an instance of DateTime.
public struct DateOnly
{
public int Day { get; set; }
public int Month { get; set; }
public int Year { get; set; }
}
public static class DateOnlyExtensions
{
public static DateOnly GetDateOnly(this DateTime dt)
{
return new DateOnly
{
Day = dt.Day,
Month = dt.Month,
Year = dt.Year
};
}
}
Usage
DateTime dt = DateTime.Now;
DateOnly result = dt.GetDateOnly();
To get only the date portion use the ToString() method,
example:
DateTime.Now.Date.ToString("dd/MM/yyyy")
Note:
The mm in the dd/MM/yyyy format must be capitalized
Add Date property to the DateTime variable
var dateTime = DateTime.Now
var onlyDate = dateTime.Date
Or You can use DataType annotation as well.
[DataType(DataType.Date)]
public DateTime dateTime {get; set;}
The DataType annotation is inside the System.ComponentModel.DataAnnotations namespace.

Categories

Resources