Retrieve a string from database and compare with date - c#

I have a field in database stored as string and i need to convert it back to datetime and then compare if it equals to date. Below is the current implementation I have presently.
var date = DateTime.UtcNow ;
var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Central Africa Standard Time");
DateTime currentTime = TimeZoneInfo.ConvertTimeFromUtc(date, zone);
var loanDate = currentTime.Date.ToString("dd/MM/yyyy").Replace("-", "/");
if (DateTime.ParseExact(firstRepay, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date.ToString("dd/MM/yyyy").Replace("-", "/") == WATTime.Date.ToString("dd/MM/yyyy").Replace("-", "/"))
{ // Do this
}
note that the firstRepay is in the format 06/02/2021 in the database but it might be 06-02/2021 depending on server format.

Assuming loanDate and dbDate are in the same format "dd/MM/yyyy" and the dbDate also can be in "dd-MM/yyyy" format, you can try this code
var dateFromDb="01-02/2021"; // 1 Feb 2021
var loanDate="06/02/2020"; // 6 Feb 2020
var dbDate = dateFromDb.Replace("-", "/");
var dbDateTime = DateTime.ParseExact(dbDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var loanDateTime= DateTime.ParseExact(loanDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var diffDateDays=(dbDateTime-loanDateTime).Days; // = 361
//or you can use it this way:
if ((dbDateTime-loanDateTime).Days > 0) //.... then
If dates are in a different string format you just have to change string
"dd/MM/yyyy" to "MM/dd/yyyy" for example for this date, but the algorithm will be still the same.

Please try to use like below.
string dateString = "21-Jan-2021";
DateTime otherDate=new DateTime(2021,3,3);
// Convert a null string.
DateTime mydateTime;
if(DateTime.TryParse(dateString, out mydateTime))
{
//dateString is converted to DateTime in mydateTime
if(mydateTime==otherDate)//Check with exact Date and time
{
//DB date and other date is equal
}
if(mydateTime.Date==otherDate.Date)//Check with Only date
{
//DB date and other date is equal
}
}
Note: Learn different way to convert string to DateTime How to Convert String To DateTime in C#.

Which database you are using, you should directly parse date in your SQL query.
Below is sample for SQL Server
SELECT CAST('06/02/2021' as date) as MyDate
SELECT CAST(REPLACE('06-02/2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-02-2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-February-2021','-','/') as date) as MyDate
All these will return date which will be directly casted as DateTime in C#. You can parse all your rows using SQL statement at once.
If you have space or some extra chars that can be managed by trim/ regex.

Related

Convert time string to DateTime in c#

How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);

DateTime.Parse Not Parsing

I'm trying to return the date as "2015-06-18"
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
This returns "2015/06/18 hh:mm:ss"
What am I missing?
If you want a particular output format, you can specify one yourself.
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
string output = newDate.ToString("yyyy-MM-dd");
Console.WriteLine (output); // produces 2015-06-18 right now
The DateTime structure in .net always includes the time of day, and there is no built-in way to store only a date, so if you want to exclude it, you'll need to use the formatting options.
What you need is to format the datetime object.
newDate.ToString("yyyy-MM-dd") -> 2015-06-19
Why don't you just use the DateTime.Date property?
DateTime date1 = DateTime.Now;
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("yyyy-MM-dd"));

DateTime string format in c#

I have a project that contain 3 string variables.
DateFormatStr is the format string I need to use to output dates.
DateFormatFrom is the start date a request will apply from
FilloutDateTo is the end date the request will apply to.
The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?
string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";
So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.
Thanks
If I understand correctly, you can use DateTime.Today property like;
var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);
and use DateTime.ToString() to format them like;
var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Results will be;
12/04/2014 00:00:00
12/04/2014 23:59:59
You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime startOfDay = DateTime.Today;
DateTime endOfDay = DateTime.Today.AddDays(1).AddTicks(-1);
string dateFormatFrom = $"{startOfDay: MM/dd/yy hh:mm:ss tt}";
string filloutDateTo = $"{endOfDay: MM/dd/yy hh:mm:ss tt}";
string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

parse date in mm_dd_yyyy format

I need to parse date in the following format.
mm_dd_yyyy
I know I can do like this
var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
and then replace the -with underscore character.
But is there any other way around to do the same?
So, what's the problem?
Just make appropriate format string: MM_dd_yyyy.
var dateTime = DateTime.ParseExact("08_02_2005", "MM_dd_yyyy", CultureInfo.InvariantCulture); // from string to DateTime
var s = dateTime.ToString("MM_dd_yyyy"); // from DateTime to string

Categories