Formatting Date and Time with a function in C# - 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:

Related

DateTime conversion from UI

I have a form where the user selects the Date from the UI .
I am getting the following value from UI
var uiDate = "2019-05-03T00:00:00.000Z".
I need to convert this to DateTime for further processing .
var dt = Convert.ToDateTime(uiDate);
The value of dt is "5/2/2019 8:00:00PM" .
As we can see I am always getting one day back after DateTime conversion from the date selected from UI. I was expecting "5/3/2019".
I am not able to figure out why is this happening after DateTime conversion?
Convert.ToDateTime is implicitly converting the value to local time. If you use DateTime.ParseExact, you can specify appropriate conversion options:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string text = "2019-05-03T00:00:00.000Z";
DateTime parsed = DateTime.ParseExact(
text, // The value to parse
// The pattern to use for parsing
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
// Use the invariant culture for parsing
CultureInfo.InvariantCulture,
// Assume it's already in UTC, and keep it that way
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(parsed); // 03/05/2019 00:00:00 (on my machine; format will vary)
Console.WriteLine(parsed.Kind); // Utc
}
}

how to compare datetime value from database with textbox datetime value

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.

Checking if String is a proper date and insert it into database

I store in database value of date.
I display the current date in format:
textBoxTradeDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
I want insert this date into database. How to check if it is proper value? I don't want use Regular Expression and I need to save this textBoxTradeDate.Text in database. Also, the user must be able to change this date, so I can't store DateTime.Now and only display date part.
I don't want use Calendar tool.
Use TryParseExact, so that you can specify the date format:
DateTime tradeDate;
bool ok = DateTime.TryParseExact(
textBoxTradeDate.Text,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out tradeDate
);
if (ok) {
// correct date, so you can put it in the database
} else {
// incorrect format, so tell the user
}
You can use DateTime.TryParse().
But you should ensure that you specify the expected date format if there is the possiblity of a problem.
string datestr = "2001-01-01";
DateTime date;
if (DateTime.TryParse(datestr, out date)) {
//write date to db
} else {
//throw an error
}
so I cant store DateTime.Now and only display date part.
SQL Server's date type with mapped DateTime type of .NET Framework. That's why you should insert your datetime value directly date typed column and this column saves only date part of it.
Since you always passing your formatted DateTime.Now to textBoxTradeDate.Text property, you can just pass this DateTime.Now value directly your parameterized insert query.
If you wanna check your textBoxTradeDate.Text is a valid DateTime, there are DateTime.Parse, DateTime.TryParse, DateTime.ParseExact and DateTime.TryParseExact methods which they are exactly what this for.
string s = textBoxTradeDate.Text;
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// You have a valid datetime.
}

String to Date parsing

I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);

convert DateTime to string according to customCultureInfo in G((combination of date and Time) format

I have changed my system date format to Faeroese.
I want to convert DateTime to String according to customCulture with G format (combination of date and Time)
check the below code.
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime dateTimeValue = (DateTime)value;
CultureInfo customCulture = MySettings.getCustomCulture();
//for getting custom culture in my app
//in custom culture i have changed shortDateFormat according to the user preference.
//value in shortDateFormat = dd/MM/yyyy
string result = string.Format(customCulture, "{0:G}", result);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
but i get the output with sepertators according to system DateTime not with users given format in customCulture,
i even dont find any method overloaded in string.Format() or DateTime.ToString() to do this.
If i pass CultureInfo.InvariantCulture then i cant get output in G format.
try this:
DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("G", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("nl-BE")));
According to Standard Date and Time Format Strings "G" uses short date format (as you claim to specify). So most likely reason of using local culture separator is covered in The "/" Custom Format Specifier portion of ""Custom Date and Time Format Strings".
Since your "short date format" is "dd/MM/yyyy" than instead of "/" it will use corresponding separator from the culture info (which you are likely picking from default culture).
Escaping with \ is covered in the Using the escape character portion of the same "Custom Date and Time Format Strings" article.
So you want your shortDateFormat = #"dd\/MM\/yyyy" or properly specify DateTimeSeparator in corresponding part of your custom CultureInfo.

Categories

Resources