how to convert text to date? - c#

i have this text format:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
i need to get this: dd/mm/yyyy
how to do it in C# Winform code ?
thank's in advance

You could parse it with DateTime.Parse(...) and after woods print it with DateTime.ToString().
var date1 = DateTime.Parse("8/27/2009 8:23:06 AM", CultureInfo.GetCultureInfo("en-US"));
var date2 = DateTime.Parse("Thu Aug 27 2009 12:42:22", CultureInfo.GetCultureInfo("en-US")); //Edited the date a little
var date3 = DateTime.Parse("08/12/2009 20:22", CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(date1.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date2.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date3.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Some of it is maybe redundant for you. I live in DK and have DK culture so I can't parse the same strings as you can if you have a US computer. Therefore I have set the culture explicit. If you have US culture by standard or want to adapt the application for other cultures then you can use:
//for parsing
var date1 = DateTime.Parse("A date");
//for printing
date1.ToShortDateString();
As fletcher, you can use DateTime.TryParse instead if you parse user input or data where you expect flaws in the provided date strings.

For those particular formats I would use the DateTime.TryParse function. I 'm pretty sure only the final string you have provided would be accepted by the parse operation, the TryParse function will return a boolean value indicating the success of the operation. Once you have the resulting DateTime object you can then output a string in ShortDate format using the ToShortDateString function or you can specify a different format if you wish.
DateTime date = new DateTime();
bool parseSucceeded = DateTime.TryParse("08/12/2009 20:22", out date);
if(parseSucceeded)
Console.WriteLine(date.ToShortDateString());

DateTime.Parse("text")

Related

String format to convert datetime causes an error

I try to convert persiandate to standard date.So my persian date has these formats (it means the user can enter these formats :
1392/1/1
1392/01/01
1392/01/1
1392/1/01
So i write a function to convert my persian date to standard date like this :
public DateTime ConvertPeersianToEnglish(string persianDate)
{
string[] formats = { "yyyy/MM/dd" };
DateTime d1 = DateTime.ParseExact(persianDate, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
PersianCalendar persian_date = new PersianCalendar();
DateTime dt = persian_date.ToDateTime(d1.Year, d1.Month, d1.Day, 0, 0, 0, 0, 0);
return dt;
}
But these function just can handle this formats 1392/01/01 and of the users enter other formats i got this error:
String was not recognized as a valid DateTime
Best regards
You're specifying MM and dd in your format, which require two digits. Just specify "yyyy/M/d" as the format - that should handle both 1 and 2-digit day/month values. (You can specify multiple formats instead, but in this case you don't need to. You might want to consider doing that just to be clear, but M and d will both handle two digit values with a leading zero with no problems.
Note that if you're just specifying a single format, you don't need to put it in an array. You can just use:
string format = "yyyy/M/d";
DateTime d1 = DateTime.ParseExact(persianDate, format,
CultureInfo.CurrentCulture,
DateTimeStyles.None);
However:
I suspect you want to specify the invariant culture, given that you don't want this value to affected by the culture
Your current approach of converting a date to the Persian calendar will simply not work.
Currently you're implicitly validating that the date given is in the Gregorian calendar, but then you're treating it as a Persian date. For example, 1392/02/30 is a valid Persian date, but not a valid Gregorian date.
Instead, you should use a culture which already uses the Persian calendar, and then specify that as the culture in your DateTime.ParseExact call. Then you don't need to do anything else afterwards.
You might alternatively want to consider using my Noda Time library - version 1.3 which includes the Persian calendar should be released in the next day or two.
Sample code using Noda Time:
var persian = CalendarSystem.GetPersianCalendar();
// The pattern takes the calendar system from the default value
var sampleDate = new LocalDate(1392, 1, 1, persian);
var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy/M/d")
.WithTemplateValue(sampleDate);
var date = pattern.Parse("1392/02/30").Value;
Console.WriteLine(LocalDatePattern.IsoPattern.Format(date));
Specify all formats in string[] formats:
string[] formats = { "yyyy/MM/dd", "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd" };
But these function just can handle this formats 1392/01/01
Because your yyyy/MM/dd format only support this value.
If your input can be
1392/1/1
1392/01/01
1392/01/1
1392/1/01
values, you should provide all formats that support these in your formats array in your DateTime.ParseExact method.
string[] formats = { "yyyy/MM/dd", "yyyy/M/dd", "yyyy/MM/d", "yyyy/M/dd" };
With these formats, if your value matches one of these formats, your parsing will be succeeded.

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

how to get desired datetime format

i want to generate current date and time in a format like this Mon, 10/08/12 12:29:39 . But when i used a code shown below
DateTime date = DateTime.Now;
i am getting like 10/8/2012 12:29:39 PM , but i actually want a format like Mon, 10/08/12 12:29:39 , what change in this code i can use to get the desired output.
I did this code also ,but didnt success
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
Console.WriteLine(time.ToString("ddd, MM/dd/yy hh:mm:ss"));
string format = "ddd, MM/dd/yy HH:mm:ss";
Don't forget to provide the Culture (or the InvariantCulture) as a formatting parameter. Otherwise it will default to the UI culture which might not always provide the format that you expect.
string format = time.ToString("ddd, MM/dd/yy hh:mm:ss", CultureInfo.InvariantCulture);
you should read this page for the future
Custom Date and Time Format Strings:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
you can use this code for all detail datetime
string inp;
DateTime inpdate = DateTime.ParseExact(inp, "dd/mm/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
and u too use this code for with out time
ret = pc.ToDateTime(Convert.ToInt32(inp.Split('/')[2]), Convert.ToInt32(inp.Split('/')[1]), Convert.ToInt32(inp.Split('/')[0]), 0, 0, 0, 0);
You can specify the format either by using one of the built in Methods for example:
.ToShortDateTimeString();
or specifying a string format in the parameter of the .ToString() method.
Example:
.ToString("hh/MM/yyyy");
you can find all the available string formats on the MSDN page, or if you simply google it.

Get DateTime Obj from "mm/yyyy" format Date string

I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)

string to DateTime conversion in C#

Stupid questions but cant get my head around it...
I have a string in this format 20081119
And I have a C# method that converts the string to a DateTime to be entered into a SQL Server DB
public static DateTime MyDateConversion(string dateAsString)
{
return System.DateTime.ParseExact(dateAsString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
}
The problem is that the Date is coming out like this: Date = 19/11/2008 12:00:00 AM and I need it to be a DateTime of type yyyyMMdd as I am mapping it into a schema to call a stored proc.
Thanks in advance guys.
Cheers,
Con
There is no such thing as "a DateTime of type yyyyMMdd"; a DateTime is just a large integer, indicating the amount of time in an epoch - it doesn't have a format. But that is fine, since you should be using parametrized TSQL anyway - so just add the DateTime as the value of a DbParameter, and it will be handed to the db in an unambiguous way (don't use string concatenation to build a TSQL command):
DbParameter param = cmd.CreateParameter();
param.ParameterName = "#foo";
param.DbType = DbType.DateTime;
param.Value = yourDateTime; // the DateTime returned from .ParseExact
cmd.Parameters.Add(param);
or for a SqlCommand:
cmd.Parameters.Add("#foo", SqlDbType.DateTime).Value = yourDateTime;
If you genuinely need a string, then just use the string directly as a [n][var]char parameter.
Also - in this case, to parse the date I would use the invariant culture (since culture doesn't feature in the format):
DateTime yourDateTime =
DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture);
From the conversation, it seems you might also need to go from a DateTime to a string, in which case simply reverse it:
string dateString = yourDateTime.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
Date Time is a class that, by default, formats it's ToString as 19/11/2008 12:00:00 AM
This is from MSDN which may help you
Because the appearance of date and
time values is dependent on such
factors as culture, international
standards, application requirements,
and personal preference, the DateTime
structure offers a great deal of
flexibility in formatting date and
time values through the overloads of
its ToString method. The default
DateTime.ToString() method returns the
string representation of a date and
time value using the current culture's
short date and long time pattern. The
following example uses the default
DateTime.ToString() method to display
the date and time using the short date
and long time pattern for the en-US
culture, the current culture on the
computer on which the example was run.
You may be able, therefore, to overload the ToString on DateTime to the desired format, else pass the string representation directly to the stored procedure instead
Ok, back to the culture thing... When you say:
the Date is coming out like this: Date
= 19/11/2008 12:00:00 AM
I'm guessing you are running a ToString on the date to see this result? The formatting in ToString will vary based on the culture and will use your current culture by default.
I was able to reproduce the format your are getting by doing this:
var dateString = "20081119";
var fr = new System.Globalization.CultureInfo("fr-FR");
var resultingDate =DateTime.ParseExact(dateString,"yyyyMMdd",System.Globalization.CultureInfo.CurrentCulture);
Console.WriteLine(resultingDate.ToString(fr));
You have a valid date, so the formatting shouldn't matter, but if it does and you need to get it in the format you described, then you need to format it when converting to a string... if it's already a string, then there is no need for the date conversion.
I could be mis-reading your question, but I had to get this out b/c it was bugging me.
I'm thinking it's due to the culture set in CurrentCulture, without knowing what that is, I can't be certain, but specifying en-US works on my end. Here is the code I have:
var dateString = "20081119";
var enUS = new System.Globalization.CultureInfo("en-US");
var resultingDate = DateTime.ParseExact(dateString,"yyyyMMdd",enUS);
Console.WriteLine(resultingDate.ToString());
Give it a try and see if it works for you.
This is what will give exact result you are looking for:
convert( varchar(10), getdate(), 112 ) : datetime to string (YYYYMMDD format)
convert( datetime, '20081203', 112 ) : string to datetime (YYYYMMDD format)
Code side:
DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat;
Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008 (use similar formats acc to your requirements)
or
date1.ToString("YYYYMMDD",CultureInfo.CreateSpecificCulture("en-US"))
date1.ToString("YYYYMMDD");
Details at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Categories