Parsing Custom DateTime Format - c#

I have to parse DateTime objects from strings with the yyyyMMddhhmmss format.
If I run this code, it works fine:
DateTime y = new DateTime(2013, 07, 22, 15, 35, 23);
string x = y.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture);
But if I run this code - seemingly the inverse operation - I get an exception:
string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddhhmmss", CultureInfo.InvariantCulture);
The exception is:
System.FormatException: String was not recognized as a valid DateTime.
I'm stumped as to what's wrong here. What am I doing wrong?
Note: Don't worry about timezones. I can deal with getting the correct timezone later.

The problem is that the date-time format you specified uses hh for a 12-hour time format, but the input string has 15 in that area. It can't parse this because 15 is outside the expected range.
Try using HH for a 24-hour time format instead:
string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
Further Reading:
Custom Date and Time Format Strings

Related

Convert date string to DateTime format

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

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

DateTime parsing - unexpected result

I have datetime string
dateStr = "2017-03-21T23:00:00.000Z";
then I am calling
var date = DateTime.Parse(dateStr);
and unexpectedly my date equals
22.03.2017 00:00:00
I expected it to be 21.03.2017
What's going on here?
DateTime.Parse() is locale specific and will take into account your local time zone when parsing dates.
If you are in CET (Central European Time) during the winter your offset is one hour ahead of UTC. The date given is marked with a Z indicating it is in UTC, so DateTime.Parse() will adjust that to your local timezone.
There is an override that allows you to change that behaviour if you want, by specifying a specific DateTimeStyles enum. DateTimeStyles.AdjustToUniversal is what you are looking for as that should keep the DateTime as UTC.
And if you only want the date part afterwards, you can just call .Date on the DateTime object you got back from Parse()
So, something like this:
var date = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).Date;
if the date format does not change then you can use the below code to get date part from date string. But it is a bit risky due to its strict dependency on the input format.
string dateStr = "2017-03-21T23:00:00.000Z";
int year = Int32.Parse(dateStr.Substring(0, 4));
int month = Int32.Parse(dateStr.Substring(5, 2));
int day = Int32.Parse(dateStr.Substring(8, 2));
var date = new DateTime(year, month, day);
Console.WriteLine(date);
Because the format of type 'DateTime' variable is 'YYYY-MM-DD hh:mm:ss'.
If you run this code:
var dt = DateTime.Now;
Console.WriteLine(dt);
You'll see '24/03/2017 12:54:47'
If you have 'YYYY-MM-DD' format, add .ToString("dd-MM-yyyy"), then:
string dateStr = "2017-03-21T23:00:00.000Z";
var date = DateTime.Parse(dateStr).ToString("dd-MM-yyyy");
Result:'24-03-2017'

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

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

Categories

Resources