I am trying to convert my date string to MonthDate format
Date string is in this format "08-07-2016 00:00:00"
I need this output: July 8
I am trying String.Format("{0:ddd, MMM d, yyyy}", dt) but it is not working.
replace
String.Format("{0:ddd, MMM d, yyyy}", dt)
with
String.Format("{0:MMMM d}", dt)
MMMM is the name of the month
d is the day without leading 0
Reference: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Try this:
string.Format("{0:MMMM d}", dt);
In C# 6.0 you can do it like this:
$"{dt:MMMM d}";
With "MMM" you get the short version of each month. With "MMMM" you get the full name.
Have you tried the following?:
date.ToString("MMMM d")
Example:
DateTime date = DateTime.Parse("08-07-2016 00:00:00");
Console.WriteLine(date.ToString("MMMM d"));
Results to:
July 8
If your date is a string, try this :
string myDate = "08-07-2016 00:00:00";
DateTime myDateValue = DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None);
string myDateString = string.Format("{0: MMMM d}", myDateValue);
Related
How can I convert the following strings to a System.DateTime object?
Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010
Normally something like the following would do it
DateTime dt;
DateTime.TryParseExact(value, "dddd d MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
but this doesn't work because of the 'th', 'st' or 'rd' in the string
Update
It appears that DateTime doesn't support formatting the 'th', 'st', 'rd' etc so they need to be stripped before parsing. Rubens Farias provides a nice regular expression below.
What about strip them?
string value = "Wednesday 13th January 2010";
DateTime dt;
DateTime.TryParseExact(
Regex.Replace(value, #"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
"dddd d MMMM yyyy",
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None, out dt);
Another approach.
string sDate = "Wednesday 13th January 2010";
string[] sFields = sDate.Split (' ');
string day = sFields[1].Substring (0, (sFields[1].Length - 2));
DateTime date = new DateTime (sFields[3], sFields[2], day);
Another alternative using escape characters for handling (st, nd, rd, and th) without stripping them before the call of DateTime.TryParseExact
string dtstr = "Saturday 23rd January 2016";
DateTime dt;
string[] formats = new string[] {
"dddd d\\s\\t MMMM yyyy", "dddd d\\n\\d MMMM yyyy",
"dddd d\\r\\d MMMM yyyy", "dddd d\\t\\h MMMM yyyy" };
bool result = DateTime.TryParseExact(dtstr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Where does "th", "st","nd" or "rd" appear below?
monday
tuesday
wednesday
thursday
friday
saturday
sunday
january
february
march
april
may
june
july
august
september
october
november
december
However you know those 4 will always be followed by a space. So unless I've missed something, a simple
value = value.Replace("August","Augus").Replace("nd ","").Replace("st ","").Replace("nd ","").Replace("rd ","").Replace("Augus","August");
DateTime dt;
DateTime.TryParseExact(value,"DDDD dd MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
No credit to me but this looks interesting for general DataTime parsing: http://www.codeproject.com/KB/datetime/date_time_parser_cs.aspx?msg=3299749
I remembered this post on using MGrammar to parse a lot of different ways to express dates and times. It doesn't exactly answer your question, but it might serve as a useful base depending on what your ultimate goal is.
Expanding on Kenny's approach, I added some code to pass integers to the DateTime variable...
string sDate = "Wednesday 13th January 2010";
string[] dateSplit = sDate.Split (' ');
string day = dateSplit[1].Substring(0, dateSplit[1].Length - 2);
int monthInDigit = DateTime.ParseExact(dateSplit[3], "MMMM", CultureInfo.InvariantCulture).Month;
DateTime date = new DateTime(Convert.ToInt16(year), monthInDigit, day);
I am trying to get this date string 09 Apr 2015: 15:16:17 to display in this format 09/04/2015 15:16:17. This is what I have tried.
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
DateTime.TryParse(dateString, out dateValue);
dtDateTime = dateValue;
This is the output 01/01/0001 00:00:00
I thought the TryParse would convert the dateString value to the required DateTime format. What am I doing wrong?
You should go with this:
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, #"dd MMM yyyy':' HH':'mm':'ss",
new CultureInfo("en-us"), DateTimeStyles.None, out dateValue))
dtDateTime = dateValue;
Using TryParseExact you can provide a custom date format string to match your input date. In the example above I added that extra : after the year.
Also, you must use a CultureInfo which can understand your month name; here I assumed you got an english formatted date.
You need to specify the format since it's not a standard date format string:
DateTime.TryParseExact(
dateString,
"dd MMM yyyy: HH:mm:ss",
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out dateValue);
Also, you should check the result of the call since TryParse and TryParseExact return true/false
You can use TryParseExact method:
DateTime.TryParseExact(dateString, "dd MMM yyyy: HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AllowWhiteSpaces,
out dtDateTime);
Tips:
If you use MMM, the month will be treated as if it is in 3 letter format (like Apr )
If you use HH rather than hh it means the hour part is in 24-hour format, the it will not fail on parsing 15 as hour
i have a string date in the following format
Thu Jan 5 19:58:58 2012
I need to parse this string to System.DateTime TimeReceived variable using DateTime.Parse() method.
Any one knows how to parse this string?
You could use the TryParseExact method which allows you to specify a format:
var str = "Thu Jan 5 19:58:58 2012";
DateTime date;
if (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the date was successfully parsed, you could use the date variable here
Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);
}
if you look at the ParseExact function, about halfway there's
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
so if you'd switch those around to match what you want, you'll end up with
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
dateString = "Thu 5 Jan 19:58:58 2012";
format = "ddd MMM dd hh:mm:ss yyyy";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);
That should work fine.
I have a short program which converts a string to both date and time format from a simple string.
However it seems that the String is not recorgnizable for the system to be converted into date time format due to the sequence of the string. The String that should be converted is an example like : "Thu Dec 9 05:12:42 2010"
The method of Convert.ToDateTime have been used but does not work.
May someone please advise on the codes? Thanks!
String re = "Thu Dec 9 05:12:42 2010";
DateTime time = Convert.ToDateTime(re);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Take a look at DateTime.TryParseExact
DateTime time;
if (DateTime.TryParseExact(re,
"ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.None, out time)) {
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
} else {
Console.WriteLine("'{0}' is not in an acceptable format.", re);
}
It is often necessary to give it a hint about the specific pattern that you expect:
Edit: the double-space is a pain, as d doesn't handle that;
DateTime time = DateTime.ParseExact(re.Replace(" "," "),
"ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Take a look at DateTime.Parse
Try this
DateTime time = Convert.ToDateTime("2010, 9, 12, 05, 12, 42");
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Not sure if the string input should have the double space but you could pull that out and use geoff's answer.
re = Regex.Replace(re, #"\s+", " ");
Other option is to adjust his match string accordingly.
DateTime time = DateTime.ParseExact(re, "ddd MMM d HH:mm:ss yyyy", CultureInfo.CurrentCulture);
I have a program which converts a irregular date and time string into a system DateTime.
However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.
There are only 2 types of date time strings that the program needs to convert:
Thu Dec 9 05:12:42 2010
Mon Dec 13 06:45:58 2010
Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.
May someone please advise on the codes? Thanks!
The codes:
String rb = re.Replace(" ", " 0");
DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):
DateTime result;
string dateToParse = "Thu Dec 9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";
if (DateTime.TryParseExact(
dateToParse,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out result)
)
{
// The date was successfully parsed => use the result here
}
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.
You can use this Regex statement with named groups to make it easier
((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
This is sample code which you can try:
var str = "Thu Dec 9 06:45:58 2010";
if (str.IndexOf(" ") > -1)
{
str = str.Replace(" ", " ");
DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
}
else
{
DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
}