Parse C# string to DateTime - c#

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?

Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.

You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);

string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Related

C#: Is this possible to convert 24hrs format string Datetime to 12hrs AM/PM dateformat (again in string only)

I have a date/time return from a C# method is in string,
string dateTime = "2018-6-18 20:50:35"
Now I would like to convert this into another string representation like,
string convertDT = "2018-6-18 08:50:35 PM"
Is this possible?
Seems like I can do something like,
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
but not working. Suggestion please!
Just parse the string into a new DateTime object and then call ToString() with the right formats:
string dateTime = "2018-6-18 20:50:35";
DateTime parsedDateTime;
if(DateTime.TryParse(dateTime, out parsedDateTime))
{
return parsedDateTime.ToString("yyyy-M-d hh:mm tt");
}
The benefit of my answer is that it contains validation (DateTime.TryParse()), it results in a couple extra lines of code but you can now accept all input and not worry about an exception being thrown.
Even better would be to refactor this logic into its own method that you can re-use:
public static bool TryChangeDateTimeFormat(string inputDateString, string outputFormat, out string outputDateString)
{
DateTime parsedDateTime;
if(DateTime.TryParse(inputDateString, out parsedDateTime))
{
outputDateString = parsedDateTime.ToString(outputFormat);
return true;
}
outputDateString = string.Empty;
return false;
}
This returns a bool of whether or not the conversion was successful and the out variable will be modified depending on the result.
Fiddle here
Without adding any validation,
var string24h = "2018-6-18 20:50:35";
var dateTime = DateTime.Parse(string24h);
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
Use DateTime.ParseExact and then ToString
Sure, you can use the DateTime class to parse the original string and then output a differently formatted string for the same date:
string result = DateTime.Parse(dateTime).ToString("h:mm tt", CultureInfo.InvariantCulture);
var dateTime = "2018-6-18 20:50:35";
var dt = Convert.ToDateTime(dateTime);
var amPmDateTime = dt.ToString(#"yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
To give you exactly your format you would use
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-MM-dd hh:mm:ss tt");
You can change the format between the quotes however you would like. For example yyyy/MM/dd or something. Just remember MM is 2 spots for months and mm is 2 spots for minutes.
So if you put
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-mm-dd hh:mm:ss tt");
You are going to get year - minutes - days.

DateTime format conversion mm/dd/yyyy to yyyy/mm/dd

Can someone please let me know how do I convert this datetime format into yyyyMMdd
2/28/2017 12:02:04 AM
At the output I should get 20170228
Any advice on this?
If you already have the DateTime as an object
string formattedDate = date.ToString("yyyyMMdd");
If you need to parse the value first.
string dateValue = "2/28/2017 12:02:04 AM";
string format = "M/d/yyyy hh:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateValue, format,
System.Globalization.CultureInfo.InvariantCulture);
For reference you can find a breakdown of the Custom Date and Time Format Strings
You need to specify the format of the date.
If you want it for the current time you can try like this :
string dtime = DateTime.Now.ToString("yyyy/MM/dd");
This is the solution I have come up with for you:
string format = "M/d/yyyy hh:mm:ss tt";
string dateString = "2/28/2017 12:02:04 AM";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(dateString, format, provider);
string output = date.ToString("yyyyMMdd");
If you're using C# 6 or later (VS2015), you can format DateTime objects easily by using string interpolation using a custom format string. The custom format string that you're looking for is "yyyyMMdd".
// create your preferred date and time in a new DateTime struct
DateTime yourDateTime = new DateTime(2017, 2, 28, 0, 2, 4);
// format yourDateTime as a string
string yourFormattedDateTime = $"{yourDateTime:yyyyMMdd}";
You can read more about interpolated strings at https://msdn.microsoft.com/en-us/library/dn961160.aspx, and, as previously mentioned by #Adam Carr, you can find more information on custom date and time format strings at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Converting string to date time by parsing

I am getting a string in the following format
string dt= "\"2014-06-01T05:00:00.000Z\""
I am trying to convert it to Date following way
mDateTime dt = Convert.ToDateTime(dt)
I get error saying When converting string to date time use parse the string.
Please let me know how I can parse the string to date. Thanks
Convert.ToDateTime method fails because this is not a standard date and time pattern for your CurrentCulture (And probably no culture support this format).
You can use custom date and time formatting with DateTime.TryParseExact or DateTime.ParseExact methods.
Here an example on LINQPad;
string s = "\"2014-06-01T05:00:00.000Z\"";
DateTime dt;
if(DateTime.TryParseExact(s, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump();
}
Output will be;
6/1/2014 5:00:00 AM
Here a demonstration.
At first you have to trim quotes, then parse:
DateTime result = DateTime.Parse(dt.Trim('\"'));
you can use below menioned code
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dt12 = Convert.ToDateTime(dt);
Try This:
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dtFinal = DateTime.ParseExact(dt,"yyyy-MM-ddTHH:mm:ss.fffZ",
CultureInfo.InvariantCulture);

C# string to SqlDateTime: how to set format for recognition?

I need to use
SqlDateTime.Parse(val)
where val is a string such as " 23.3.1992 00:00:00 ".
The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?
Thanks in advance!
Try this:
string val = "23.12.1992 00:00:00";
// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);
// Part to SqlDateTime then
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));
This could be done in one statement, but just separated for illustration.
Have you tried DateTime instead of SQLDateTime
DateTime d = DateTime.Parse(val);
String s = d.ToString(CultureInfo.CreateSpecificCulture("en-US"));
Can you try this ?
string valInEuropean = "23.3.1992 00:00:00";
DateTime dateInEuropean = DateTime.Parse(valInEuropean);
string valInAmerican = dateInEuropean.ToString("yyyy-MM-dd HH:mm:ww");
For converting a string to datetime object when the format is known(in this case )
use
DateTime dwweek = DateTime.ParseExact("23.3.1992 00:00:00", "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

string to MM/dd/yyyy

I have a string like this:
3/4/2013 or like this 11/10/2012. This is in mm/dd/yyyy format which I want to convert to MM/dd/yyy. I am doing like this:
DateTime publicationDate = DateTime.ParseExact(myDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
This is throwing me an error:
String was not recognized as a valid DateTime.
What is going on here?
EDIT:
After reviewing all the answers, I want to show Month and Day of the DateTime variable.
So I cannot do something like this:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy");
Having a string will not solve my problem because I am using this variable to show only day and month.
When I tried parsing this 'publicationDate' back to DateTime is truncates the '0's from month and day.
Hope I made my point here.
Answered:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd");
You should add leading zeroes to the month and day.
This way: 04/03/2013
var myDateTime = DateTime.ParseExact(
"03/04/2013",
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
If leading zeroes are a problem, then do:
var myDateTime = DateTime.ParseExact(
"3/4/2013",
"M/d/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
Finally, if you want to add leading zeroes:
string myFormattedDateTime = DateTime.ParseExact(
"3/4/2013",
"M/d/yyyy",
System.Globalization.CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy");
Use this pattern instead: "M/d/yyyy" to parse it and "MM/dd/yyyy" for ToString:
DateTime publicationDate = DateTime.ParseExact(dt, "M/d/yyyy", CultureInfo.InvariantCulture);
// if you want to display two digits for day and month:
Console.WriteLine(publicationDate.ToString("MM/dd/yyyy"));
It works for both as you can see here: http://ideone.com/M7luBD
Simple solution was this:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd");
Thank you all for your answers!
Convert your string ToDateTime first. Make sure you have leading zeroes.
string date = "03/04/2013";
DateTime dt = Convert.ToDateTime(date);
[TestCase("3/4/2013", 3, 4, 2013)]
[TestCase("11/4/2013", 11, 4, 2013)]
public void DateTest(string date, int month, int day, int year)
{
var publicationDate = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
Assert.AreEqual(day, publicationDate.Day);
Assert.AreEqual(month, publicationDate.Month);
Assert.AreEqual(year, publicationDate.Year);
}
Both test cases pass.
If your format asks for MM/dd/yyyy then you need to supply the string as such (04/03/2013 instead of 4/3/2013). So either
use M/d/yyyy if your supplied date is without leading zero's
or use the MM/dd/yyyy if you can supply leading zero's

Categories

Resources