Converting DateTime format - c#

I am trying to convert a string, 20151107 to the date format of 2015-11-07.
Here's my code :
public static DateTime CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt;
}
However this returns something like this 11/07/2015 12:00:00 AM.
Any idea?

Your date returns like that because you are returning the entire DateTime object and since you are not providing a time it is default to 00:00:00.00.
If you want to return the Date in a particular format, you can use the Standard Format Strings or a Custom Format String.
In your case, you want 2015-11-07 which is a custom format of yyyy-MM-dd and can be used like so:
public static string CustomDateFormat(string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MM-dd");
}

public static String CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MMM-dd");
}

Related

Error: String was not recognised as a valid Datetime format [duplicate]

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

c# Date format - UK and US

I don't understand why I am finding this such a problem.
I have a simple form with a DateTimePicker on it (called dtpStartDate). I want to have two DateTime objects: one for UK format and one with US format. Something like:
string str = "31/01/2018 10:00:00"; //dtpStartDate.Value.Date.ToString()
DateTime dtUK = DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss", null);
DateTime dtUS = Convert.ToDateTime(dtUK, new CultureInfo("en-US"));
What am I doing wrong? Nothing I have tried has given me what I want, which is two DateTime objects, not a string containing the date and time.
Many thanks
Think of a DateTime object as:
public class DateTime
{
public int Year;
public int Month;
public int Day;
public int Hours;
public int Minutes;
public int Seconds;
public int Milliseconds;
}
That's all it stores, it doesn't contain any Culture-related information. If you were to create two DateTime objects "for UK Format and US Format", they would be identical and contain the same data.
However, when you call the ToString() method on a DateTime object, you can pass it a CultureInfo parameter. That parameter tells the DateTime object how to output those values into the resultant string.
So for a UK CultureInfo with ToString(new CultureInfo("en-GB"), it outputs a string containing dd/MM/yyyy HH:mm:ss.
And for a US CultureInfo with ToString(new CultureInfo("en-US"), it outputs a string containing MM/dd/yyyy HH:mm:ss.
Hope this helps
DateTime contains general datetime information. You can make a culture specific string representation. Try this:
string str = "31/01/2018 10:00:00";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss", null);
var uk = dt.ToString(new CultureInfo("en-GB")); //31/01/2018 10:00:00
var us = dt.ToString(new CultureInfo("en-US")); //1/31/2018 10:00:00 AM
string str = "31/01/2018 10:00:00"; //dtpStartDate.Value.Date.ToString()
DateTime dateTimeUK = DateTime.Parse(str, new CultureInfo("en-GB"));
DateTime dateTimeUS = DateTime.Parse(str, new CultureInfo("en-US"));

Converting string dd/mm to datetime

Converting a String to DateTime
As the above link says I can do conversion if I'm having a the complete dd/mm/yyyy,But I'm having only dd/mm not the year field.
I have achieve it by changing the date to mm/dd format and using Convert.ToDateTime(date).So any help please.
You can parse that string. Just remember that the Month part is MM not mm (minutes)
string data = "01/01";
DateTime dt;
DateTime.TryParseExact(data, "dd/MM", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);
Console.WriteLine(dt.ToLongDateString());
Of course the missing year is assumed to be the current year
You can use this source to learn more about specifiers for parsing custom date's.
Put your string variable instead of CustomDate field.
DateTime d = DateTime.ParseExact(CustomDate, "dd/MM",System.Globalization.CultureInfo.CurrentCulture);
I would use the function DateTime.TryParseExact since you can use it within an If - else structure very easily
private DateTime date;
private myString = "23/04";
if (DateTime.TryParseExact(myString, "dd/MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
myDate = date;
}
else
{
//do nothing
}
With this you can catch errors when parsing the string.

Format DateTime object from System time format to required format

My system time is of the format dd-MMM-yy (02-Dec-16). The format I want to convert it to is "yyyy/MM/dd". I've basically been playing around with all the other datetime formats that my system offers and this is the parsing statement I've figured out that works for All of them (except this) -
CultureInfo provider = CultureInfo.InvariantCulture;
string date_format = "yyyy/MM/dd HH:mm:ss tt";
DateTime now_value = DateTime.ParseExact(DateTime.Now.ToString(date_format), date_format, provider);
return now_value.ToString(date_format);
But this doesn't work for the aforementioned dd-MMM-yy format. Can someone please tell me what I am doing wrong here?
(Sidebar -Is there a more efficient way in which I can write this above snippet?)
You don't need to convert DateTime to string and then convert back to DateTime and again back to string, if you have DateTime input just call the ToString with the format as below
string dt =DateTime.Now.ToString("yyyy/MMM/dd", CultureInfo.InvariantCulture);
for your example :
DateTime now_value = DateTime.ParseExact("02-Dec-16", "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
return now_value.ToString("yyyy/MM/dd");
Try This:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format,CultureInfo.CreateSpecificCulture("en-US"));
return date_now;
Even This should also work:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format);
return date_now;
I think best way would be to create an extension method for multiple date formats,
var inputDate = "02-Dec-2016";
string[] availaible_input_date_format = { "dd-MMM-yyyy", "dd/MMM/yyyy" }; // add as many formats availible
var date_format = "yyyy/MMM/dd";
DateTime outputDate;
DateTime.TryParseExact(inputDate, availaible_input_date_format, null, DateTimeStyles.None, out outputDate);
Console.WriteLine(outputDate.ToString(date_format));
You can try this:
datetime yourdatetime = new datetime();
string converteddatetime = yourdatetime.toString("yyyy/MM/dd");

String to DateTime conversion as per specified format

I would like to have my end result in date format as per the specified format i.e YYMMDD how can i get this from a string given as below
string s="110326";
From string to date:
DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
Or the other way around:
string s = d.ToString("yyMMdd");
Also see this article: Custom Date and Time Format Strings
DateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
although id recommend
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
// Process
}
else
{
// Handle Invalid Date
}
To convert DateTime to some format, you could do,
string str = DateTime.Now.ToString("yyMMdd");
To convert string Date in some format to DateTime object, you could do
DateTime dt = DateTime.ParseExact(str, "yyMMdd", null); //Let str="110719"

Categories