how to compare datetime value from database with textbox datetime value - c#

I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.

you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp

You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.

string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}

As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.

Related

Formatting Date and Time with a function in C#

So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.
I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.
This is my function code:
private static string FormatDateTime(object ObjInstallDate)
{
object FinalDate = DBNull.Value;
string strDate = Convert.ToString(ObjInstallDate);
DateTime dtm;
DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);
if (!String.IsNullOrEmpty(strDate))
{
FinalDate = dtm;
}
return FinalDate.ToString();
}
Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?
Taking a substring does the job (if the format is always like shown):
DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out DateTime dtm);
To get the required format to present the result you can use
dtm.ToString("yyyy-MM-dd");
After looking at your code and question it looks like the date you are passing to the function is not in correct/expected format that c# supports, that's why it is giving you the default system's beginnning date which is 01-01-0001 00:00:00 here.
But, as a workl around, as I can observe first 8 digit of the input value is date part, so you can use that in following way:
DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);
return dtm.ToString("yyyy-MM-dd");
You only needed to make sure your format matched your input, which none of your provided input formats did.
See how the custom dateformat specifiers and literal characters line-up with your input.
Your input: 20161216000000.000000-000
format specifiers: yyyyMMddhhmmss.ffffff-000
Bringing that format to your method you'll get this:
// takes an object, returns a DateTime or null in case of failure
DateTime FormatDateTime(object ObjInstallDate)
{
DateTime dtm;
if (!DateTime.TryParseExact(
(string) ObjInstallDate, // notice that we don't hassle with the input here,
// only cast to a string
// we simply rely on the parser of DateTimer.TryParseExact
"yyyyMMddhhmmss.ffffff-000", // this matches the format
// if the -000 represents a timezone
// you can use z00 or zz0
// don't use zzz as that expects -0:00
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dtm))
{
// an invalid date was supplied, maybe throw, at least log
Console.WriteLine("{0} is not valid", ObjInstallDate);
}
// we either return here null or a valid date
return dtm; // !! No ToString() here
}
I cherry picked the needed custom format value from Custom Date and Time Format Strings.
Notice that I simply return the DateTime instance that was created. You'll see next why I do that.
As you want to display the DateTime on a Winform (I assume in a textbox, but an label will work as well) you can now simply Databind the DateTime instance to the textbox and let the databinding plumbing do the formatting. Here is a code example that can be run in LinqPad:
// take a string and make a date of it
var str = "20161216000000.000000-000";
DateTime dtm = FormatDateTime(str);
// show it on a Databind TextBox
var f = new Form();
var txt = new TextBox();
txt.Width = 200;
// bind the Text property
txt.DataBindings.Add(
"Text", // property on the textbox
dtm, // our DateTime object
null, // use the DateTime instance, not a property
true, // use formatting
DataSourceUpdateMode.OnValidation,
null, // value to indicate null
"yyyy-MM-dd"); // our format
f.Controls.Add(txt);
f.Show();
I'm using the overload of Add on the DataBindingsCollection that takes an Format string. I can then use the same custom format specifier options to represent that DateTime instance however I want. From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example.
When all of this comes together this will be your result:

Converting datetime format without using SAP RFC with C#

I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}

converting messy date string to dateTime object in c#

How can I convert the String 20120313 to a DateTime object that holds the value 13-Mar-2012?
I fetch it as
DataEffectiveDate = Convert.ToDateTime(reader["date_id"]);
But it fails here already (converting to 1/1/2001)
You need to use DateTime.ParseExact:
DateTime date = DateTime.ParseExact(text, "yyyyMMdd",
CultureInfo.InvariantCulture);
Then if you want it as "13-Mar-2012", you need:
string reformatted = date.ToString("dd-MMM-yyyy");
... optionally passing in whatever culture you want to use for the month names etc.
(Another alternative is to use my Noda Time, which allows you to parse this as just a local date, without any concerns about what time it will use, time zones etc.)
When you have a particular format in mind, ParseExact is helpful:
string s = "20120313";
var when = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
There's also an overload that accepts multiple candidate formats.
Try DateTime.ParseExact:
string date = DateTime.ParseExact(reader["date_id"], "yyyyMMdd", new CultureInfo("en"));

How to Convert Date Object with Format "MM/dd/yy hh:mm:ss tt" to DateObject with Format "dd/MM/yy

I have googled alot and tried lot of solutions but nothing is working for me.For Ex i Have tried below :
public static DateTime ParseDateToSystemFormat(DateTime date)
{
IFormatProvider culture = new CultureInfo("en-GB", true);
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
return Convert.ToDateTime(dt,culture);
}
If anyone have solved this please let me know.
Date objects do not have formatting associated to them - you only use formatting for display.
When it is time to display the DateTime object, use either custom or standard format strings to format the display to your liking.
What you are doing here:
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
Is rather strange - you are getting a specific string representation of your DateTime - date.ToString("dd/MM/yyyy"), then parsing that string back to a DateTime object. A bit of a long way to say DateTime dt = date;, with clearing out the hours/minutes/seconds data.
If you simply want the date portion of a DateTime, use the Date property. It produces:
A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
The internal representation of a DateTime is always the same. There is no formatting attached to a DateTime object.
If it is only a display problem, then convert the DateTime to a string and display that string. You already know how to do it: Using ToString and specifying the format you want to have.

.NET convert Datetime to format Sortable date/time pattern ("s");

Im working with VS2008, .NET and C#, and I need to send to one of our clients a DATETIME variable.
The problem is that they want the Date in the format Sortable date/time pattern ("s").
When I get the actual datetime, it is a Datetime object. When I format it to the given format is now a String object, and it has the format I want. But after that I can't create a Datetime object from that formatted String with the same format, because it always returns it to the original Datetime format.
More specific:
DateTime currTime = System.DateTime.Now; //(the format is "13/08/2010 09:33:57 a.m.")
String date = String.Format("{0:s}", currTime);// (wanted format "2010-08-13T09:33:57")
DateTime newDate = DateTime.Parse(date);// (original format again "13/08/2010 09:33:57 a.m.")
IFormatProvider culture = new System.Globalization.CultureInfo("", true); //(Invariant Culture)
String format = "s";
DateTime fecha = DateTime.ParseExact(date, format, culture); // (original format again "13/08/2010 09:33:57 a.m.")
Is there a way of getting a Datetime object with the desired format, or Datetime objects use a given format, and you can't format them to the equivalent string formats?
Thx
A DateTime is just a number. It has no intrinsic "format". It is only rendered into a format when converted to a string. Hence, whenever you need a DateTime as a string, you have to specify what format you want it in.
String date = String.Format("{0:s}", currTime);
This can be shorted a bit to :
String date = currTime.ToString("s");
If I understand the question correctly, I think you are getting confused. A DateTime object itself is not formattable, it is essentialy just a numeric value (number of ticks since DateTime.MinValue or whatever it is).
You can convert a DateTime object into a string representation in whatever format you like, but you aren't changing the actual DateTime object.
Every time you use a DateTime value in a place where it needs to be turned into a string (e.g. in string.Format()), C# will generally call the .ToString() method. The DateTime type declares a .ToString() method that has the format you don’t want.
However, DateTime has additional methods, including .ToString(IFormatProvider provider) and .ToString(string format).
Therefore, you can probably achieve what you want if you replace every use of a DateTime variable in the relevant string-like context to one that calls the appropriate .ToString overload, for example:
Instead of
var message = string.Format("The parcel was sent on {0}.", currTime);
use
var message = string.Format("The parcel was sent on {0}.", currTime.ToString("s"));

Categories

Resources