in my code i can get 2 types of string that represents dateTime:
1."2013-09-05T15:55"
2."09-05T19:10"
How do i convert it to a valid DateTime?
i tried the following code but it throws an exception for the second format:
String departureDateStr = "09-05T19:10";
DateTime dt = Convert.ToDateTime(departureDateStr);
how do i convert the second type of string to a valid DateTime ?
do i need some kind of string manipulation?
thx,
Amir
DateTime.TryParseExact has an overload that allows you to pass multiple formats as an array. Each date string is then compared with the various formats within the array so you don't need to know ahead of time which format to look for.
string d1 = "2013-09-05T15:55";
string d2 = "09-05T19:10";
string[] formats = new string[] { "yyyy-MM-ddTHH:mm", "MM-ddTHH:mm" };
List<string> dates = new List<string>() { d1, d2 };
foreach (string date in dates)
{
DateTime dt;
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//dt successfully parsed
}
}
TryParseExact also returns false instead of throwing an exception if none of the formats in the array matched the input.
Use DateTime.ParseExact method with custom datetime format string:
string departureDateStr = "09-05T19:10";
string departureDateStr2 = "2013-09-05T19:10";
var dt = DateTime.ParseExact(departureDateStr, "MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
var dt2 = DateTime.ParseExact(departureDateStr2, "yyyy-MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
or universal call for both formats:
var dt = DateTime.ParseExact(departureDateStr, new[] { "MM-ddTHH:mm", "yyyy-MM-ddTHH:mm" }, System.Globalization.CultureInfo.InvariantCulture);
You can use DatetIme.ParseExact() method for this. It converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
String departureDateStr = "09-05T19:10";
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
DateTime parsedDate = DateTime.ParseExact(departureDateStr, format, provider);
If you need this conversion a lot of times, then you can even make it an extension method as below:
public static class StringExtensions
{
public static DateTime ToDate(this string str)
{
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
return DateTime.ParseExact(str, format, provider);
}
}
Related
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.
I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];
I am getting an error when I run the following line of code:
DateTime dt = DateTime.ParseExact(bolShipdate, "dd/MMM/yyyy", null);
The error is:
String was not recognized as a valid DateTime.
The bolShipdate value is 02-21-2016. I need to convert the date to 21-Feb-16.
How can I resolve this?
Your format in ParseExact needs to match your string. dd/MMM/yyyy doesn't match the sample data provided. try:
var bolShipdate = "02-21-2016";
DateTime dt = DateTime.ParseExact(bolShipdate, "MM-dd-yyyy", null);
Console.WriteLine(dt.ToString("dd-MMM-yy")); // Dispays 21-Feb-16
(Example fiddle)
Declaration of DateTime.ParseExact is
public static DateTime ParseExact(
string s,
string format,
IFormatProvider provider
)
Here you will want to pass the format you are parsing not the expected result. And it looks like your string is of the format MM-dd-yyyy.
You can then use .ToString(string format to get the date in your desired format:
string date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string newFormat = dt.ToString("dd-MMM-yy");
Console.WriteLine(newFormat);
Hope this can resolve:
var date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("dd-MMM-yy");
Here I want to convert date into string using tostring but when I convert it back, (string to datetime), the format is different.
static void Main(string[] args)
{
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
Console.WriteLine(dt);
Console.ReadLine();
}
expected output:
2014/12/2
But I get:
12/2/2014
string DateString = "06/20/1990";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
This will be your desire output
udpated
string DateString = "20/06/1990";;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dt = DateTime.ParseExact(DateString,"dd/mm/yyyy",culture);
dt.ToString("yyyy-MM-dd");
Call ToString with format provided when you convert DateTime instance back to string:
Console.WriteLine(dt.ToString(#"yyyy/M/d");
try this
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
use this:
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
string str = dt.ToString("yyyy/M/dd"); // 2014/12/02 as you wanted
Console.WriteLine(str);
Console.ReadLine();
As you can read here, DateTime.ToString() uses CurrentCulture to decide how to format its output (CurrentCulture of type CultureInfo provides information on how to format dates, currency, calendar etc. It is called locale in C++).
Thus, the simlplest solution as suggested by previous answers, is to use an overload of ToString() which accepts a format string, effectively overriding the CurrentCulture info:
dt.ToString(#"yyyy/MM/dd");
More on datetime formatting can be found here.
you can use
string formattedDate= dt.ToString("yyyy/M/d");
For reverse you can use
DateTime newDate = DateTime.ParseExact("2014/05/22", "yyyy/M/d", null);
So if your expected output is like : 2014/12/2
you have to use
newDate.ToString("yyyy/M/d");
This is simple, You just need to use date pattern during display
string cc = "2014/12/2";
string datePatt = #"yyyy/MM/d";
DateTime dt = Convert.ToDateTime(cc);
Console.WriteLine(dt.ToString(datePatt));
I have a string that is formatted as YYYYMMDD - how can i make a copy in the format YYYY-MM-DD?
// this is your original string
string _str = "20130101";
// you need to convert it to valid DateTime datatype
// so you can freely format the string to what you want
DateTime _date = DateTime.ParseExact(_str, "yyyyMMdd", CultureInfo.InvariantCulture);
// converting to your desired format, which is now a string
string _dateStr = _date.ToString("yyyy-MM-dd");
DateTime.ParseExact()
You'll have to parse the DateTime, then reformat it:
var input = ...
var inFormat = "yyyyMMdd";
var outFormat = "yyyy-MM-dd";
var date = DateTime.ParseExact(inFormat, input, CultureInfo.InvariantCulture);
var output = date.ToString(outFormat);
the safe approach is to convert it to DateTime Object , for example in .Net using below function :
DateTime.TryParseExact()
and then using the DateTime Object you can format it again. like below example :
dateTimeObject.ToString(YourFormatInString);
check MSDN for more details : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx