Convert date string to DateTime format - c#

I have the date string like 03/10/1999 where the format is dd/MM/yyyy (pt-BR format).
And I need to convert this date for a SQL-like format yyyy-MM-dd HH:mm:ss.fff.
I tried to use Parse and ParseExact functions, but no success so far. I will let my results below...
Using Parse
var BrazilianDate = "03/10/1999";
var Parse = DateTime.Parse(BrazilianDate, new CultureInfo("pt-BR"));
Console.WriteLine("Parsed date: " + Parse);
Output: Parsed date: 10/3/1999 12:00:00 AM
No hyphens or milliseconds...
Using ParseExact
var BrazilianDate = "03/10/1999";
var ParseExact = DateTime.ParseExact(BrazilianDate, "yyyy-MM-dd HH:mm:ss.fff", new CultureInfo("pt-BR"));
Console.WriteLine(ParseExact);
output:
Run-time exception (line -1): String was not recognized as a valid
DateTime.
Stack Trace:
[System.FormatException: String was not recognized as a valid
DateTime.] at System.DateTimeParse.ParseExact(String s, String
format, DateTimeFormatInfo dtfi, DateTimeStyles style) at
System.DateTime.ParseExact(String s, String format, IFormatProvider
provider) at Program.Main()

You need to format your output with the correct format string like this:
Console.WriteLine("Parsed date: " + Parse.ToString("yyyy-MM-dd HH:mm:ss.fff"));
//Parsed date: 1999-10-03 00:00:00.000
If you don't specify a format, .NET picks whatever it thinks is the right one (which it often isn't when you're not in the US).
You also need to strictly separate between the DateTime value and its representation in string form. No matter how you format it, the value itself will stay the same.

The format string you use in the parse method represents the format of the input string.
A DateTime does not have a display format, in fact it's a numeric value representing the number of ticks since a specific Epoch.
From official documentation:
Time values are measured in 100-nanosecond units called ticks. A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar. The number excludes ticks that would be added by leap seconds. For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight.
When parsing strings, I find it's best to either use ParseExact or TryParseExact. To print our the string representation of the DateTime value, use the overload of ToString that takes in a string that represent the format you want to display.
var BrazilianDateString = "03/10/1999";
var DateTimeValue = DateTime.ParseExact(BrazilianDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(DateTimeValue.ToString("yyyy-MM-dd HH:mm:ss.fff");

This code is working for me:
DateTime dt = new DateTime();
string x = "03/10/1999 22:10:10";
dt = DateTime.Parse(x);
Console.WriteLine(dt.ToShortDateString());
Console.WriteLine(dt.ToShortTimeString());
Console.ReadLine();
Console output:
03/10/1999
22:10
Don't use that CultureInfo, DateTime can understand spanish-brazilian dates on its own

Related

C#, DateTime conversion

Need help to convert datetime object into specific format. It may be duplicate question but i gone through many articles and question and answers provided in Stackoverflow but didn't get answer.
Current my date format is {dd/mm/yyyy 8:12:56 AM} which is default date time format. I want to convert in {mm/dd/yyyy 8:12:56 AM} format.
DateTime searchDateTime = Datetime.Now.AddYears(-1));
string test = searchDateTime.ToString("dd-MMM-yyyy");
Its giving me format which i have given in ToString.
DateTime date = Convert.ToDateTime(test);
But when i am trying to convert string to datetime format, its returning dd/mm/yyyy formatted date.
Try using DateTime.ParseExact if you want parse the string with known format and ToString when you want to represent DateTime into the desired format:
using System.Globalization;
...
DateTime searchDateTime = new DateTime(2019, 2, 25, 16, 15, 45);
// Escape delimiters with apostrophes '..' if you want to preserve them
string test = searchDateTime.ToString(
"dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
// Parse string with known format into DateTime
DateTime date = DateTime.ParseExact(
test,
"dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
// Presenting DateTime as a String with the desired format
string result = date.ToString(
"MM'/'dd'/'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
Console.WriteLine($"Initial: {test}");
Console.Write($"Final: {result}");
Outcome:
Initial: 25-Feb-2019 4:15:45 PM
Final: 02/25/2019 4:15:45 PM

string was not recognized as a valid datetime while Converting Date from Hijri to Gregorian date

I am Trying to Convert Hijri Date into Gregorian Date I was following this article and My Code is as follows :
var cultureInfo = CultureInfo.CreateSpecificCulture("ar-sa");
string date = "19/12/36 12:00:00 ص";
Getting
string was not recognized as a valid datetime
error in below line
DateTime tempDate = DateTime.ParseExact(date, "dd/MM/yyyy", cultureInfo.DateTimeFormat, DateTimeStyles.AllowInnerWhite);
lblDate.Text = tempDate.ToString("dd/MM/yyyy");
I am getting string was not recognized as a valid datetime. Please can somebody tell me whats wrong with this code?
I think I'm on the right way but.. Let's try something at least.
First of all, DateTime values are always in the Gregorian calendar, basically. There's no such thing as "A DateTime in a UmAlQuraCalendar calendar" - which is used by ar-sa culture - you have to use the UmAlQuraCalendar to interpret a DateTime in a particular way.
Second, when you use DateTime.ParseExact for parsing your string, your string and format does match exactly based on culture you use. Since ص
character seems AMDesignator of ar-sa culture, you should provide tt specifier with your time part as well.
string s = "19/12/36 12:00:00 ص";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yy hh:mm:ss tt", CultureInfo.GetCultureInfo("ar-sa"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Note: Since TwoDigitYearMax is 1451 of UmAlQuraCalendar calendar, your 36 will be parsed as 1436 with yy format specifier.
This perfectly parse your question but WAIT! What will be the result? Here it is.
02/10/2015 00:00:00
Why? As I said in the top, you have to use the UmAlQuraCalendar to interpret this DateTime instance.
UmAlQuraCalendar ul = new UmAlQuraCalendar();
Console.WriteLine(ul.GetYear(dt)); // 1436
Console.WriteLine(ul.GetMonth(dt)); // 12
Console.WriteLine(ul.GetDayOfMonth(dt)); // 19

DateTime.Parse - changes format

I'll try to illustrate an example:
var dateNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
produces: 10/01/2014 21:50:34
var dateNowParse = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
produces: 10/01/2014 9:50:34 PM
QUESTION:
How to parse the date, and keep formatting like: dd/MM/yyyy HH:mm:ss, with an 24 hour format, without any PM
Thank you!
Update 1
Sorry maybe my question wasn't so clear, i'll try to explain the real situation below.
Please do not focus on real meaning of DateTime.Now, suppose we have a string variable in the format of 10/01/2014 21:50:34, and then I try to parse it, and store the result in another variable. What I am willing to achieve is to keep the result in a DateTime variable which has the exact formatting 10/01/2014 21:50:34.
Now here is a snippet:
var stringDate = "10/01/2014 22:50:30";
DateTime parsedDate = DateTime.Parse(stringDate, CultureInfo.InvariantCulture);
//parsedDate result is: 10/01/2014 10:50:30 PM
What is frustrating me is:
In the stringDate the 22:50 hour says that the string is formatted to the 24 hour clock. (the 12 clock format uses hours counter up to 12)
If I used 22:50, Isn't logically that the output should'nt use any AM PM and 12 hour format?
How to parse the date, and keep formatting
You need to keep the format alongside the DateTime if you want to. A DateTime does not have any concept of being in a particular format. The value of the DateTime returned by Parse isn't "10/01/2014 9:50:34 PM" - it's that particular date and time, but not a string representation.
You could have a type which maintains the two together - or if you always want to format in the same way, just specify that format explicitly when you format, without keeping it as data with the DateTime value.
Personally I would try to stick to DateTime.ParseExact where feasible, as I find it easier to predict what it will do - but it does depend on your input. If it's input with a particular format that you're expecting, ParseExact really is the way forward, potentially with the invariant culture to avoid any cultural differences.
I would store the date now as a date
DateTime dateNow = DateTime.Now;
then when you need to display it with that formatting
String strNow = dateNow.ToString("dd/MM/yyyy HH:mm:ss");
If you have a date coming in with a format say in a String variable strNow and want to put it in the DateTime I would make sure to catch format exceptions
DateTime dateNow;
try {
dateNow = DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
catch (FormatException) {
//Log something or set a default date.
}
DateTime.ParseExact(DateTime, Format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
for example:
DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);

How I can get the difference by time string and Datetime now?

i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
Jun 06 2013 07:23:06
and with DateTime.Now I get the Time now. The Problem is now that i can't calculate the difference :(
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
You can use the Parse method of the DateTIme class to parse a string as a date and the subtract that from now.
TimeSpan diff = DateTime.Now - DateTime.Parse(dateString);
var hours = diff.Hours
The above exsmple of course requires the date to be in a specific format. You can if needed use DateTIme.ParseExact and specify a specific format yourself
You need to first convert your string to DateTime. here you have custom format so you can use DateTime.ParseExact or DateTime.TryParseExact method as below
DateTime dt;
if (DateTime.TryParseExact("Jun 06 2013 07:23:06", "MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// get difference
var inDays = (DateTime.Now - dt).Days;
}
You can use TimeSpan.Hours property like;
Gets the hours component of the time interval represented by the
current TimeSpan structure.
string dateString = "Jun 06 2013 07:23:06";
var differenceHours = (DateTime.Now - DateTime.Parse(dateString)).Hours;
Console.WriteLine(differenceHours);
Here a DEMO.
If you want to convert your custom formatted string to DateTime, you can use DateTime.ParseExact which need exact format matching between string and datetime.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
u may try it
DataTime diff = DateTime.Now - Convert.ToDataTime(dateString);
var hours = diff.Hours

how to convert time in string format into date time format using C#

i have textbox that accepts time format like this 12:40 PM but would like to convert it into time format like this 12:40:00 basically without the PM or AM. Here is what i have so far:
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
thanks
One option would be to parse into a DateTime and then back to a string:
string s = "12:40 PM";
DateTime dt = DateTime.Parse(s);
string s2 = dt.ToString("HH:mm:ss"); // 12:40:00
Be aware, however, that most operations work better with a DateTime versus a string representation of a DateTime.
First you should parse it to a DateTime, then format it. It sounds like your input format is something like hh:mm tt and your output format is HH:mm:ss. So, you'd have:
string input = "12:40 PM"
DateTime dateTime = DateTime.ParseExact(input, "hh:mm tt",
CultureInfo.InvariantCulture);
string output = dateTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
Note that:
I've used DateTime.ParseExact which will throw an exception if the parsing fails; you may want to use DateTime.TryParseExact (it depends on your situation)
I've used the invariant culture for both operations here. I don't know whether or not that's correct for your scenario.
I've used hh:mm, but you might want h:mm... would you expect "1 PM" or "01 PM"?
You don't parse seconds, so that part will always be 0... is that okay?
Since you are bringing it in as a string this is actually kind of easy.
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
DateTime dt = new DateTime();
try { dt = Convert.ToDateTime(StartTime); }
catch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }
StartTime = dt.ToString("HH:mm");
So you bring in your string, and convert it to a date. if the input is not a valid date, this will default it to 00:00. Either way, it gives you a string and a DateTime object to work with depending on what else you need to do. Both represent the same value, but the string will be in 24-Hour format.
Cheers!!

Categories

Resources