Convert date from MMM DD, YYYY to mm/dd/yy - c#

i got date in my db in the form of MMM DD,YYYY
String thisDate1 = "Jan 05, 2009";
in order to get arithmetic operations such as add days i have to change it to standard format i.e mm/dd/yy. how can i do this. please help

Your string is fine as-is, you can use DateTime.Parse to convert it to a DateTime object which you can do your arithmetic on, like so:
var thisDate = DateTime.Parse(thisDate1);
var nextDate = thisDate.AddDays(1);
var nextDateAsString = nextDate.ToString("MMM dd, yyyy");
Also be careful with your casing, your current string is actually in MMM dd, yyyy format. DD would actually give you the letters DD themselves, as would YYYY. mm is minutes, while MM is for months. You can find more details on this on MSDN.
Also, as #HansPassant pointed out, you don't want to be storing your dates in a string until the last possible moment.

Related

convert date time to format ddd MM/dd/yyyy HH:mm:ss

In the below code snippet I'am passing string value "item.Date" to string "Date"
I wanted to convert it to this format ddd MM/dd/yyyy HH:mm:ss.
converting to string and as well the above format was not going well i guess.
I tried using:
DateTime dateformatted = DateTime.ParseExact(item.Date, "ddd dd MMM yyyy h:mm tt", null);
it showed error. Can anyone help
foreach (var item in data)
{
model.Add(new MailDetailDTO
{
Attributes = item.Attribute1,
Date = item.Date,
From = item.SentFrom,
FromOrg = item.OrganizationName,
IsConfidential = item.IsConfidential,
MailID = item.MailHeaderID,
}
}
This is what the ParseExact API documentation on MSDN has to say :
The format of the string representation must match the specified
format exactly.
This means that there is a certain mismatch in the format you have stored the date time value in item.Date string property and the custom date time format ddd dd MMM yyyy h:mm tt which you're passing as argument to ParseExact API.
Have a look at the below code snippet:
private static void DateTimeForatError()
{
var item = "Sun 22-May-2016 3:52 AM";
DateTime dateformatted = DateTime.ParseExact(item, "ddd dd MMM yyyy h:mm tt", null); //results in exception
}
Date time string value present in item variable looks parseable but the next line results in String was not recognized as a valid DateTime. error. That is because I'm using - hyphen as the delimiter for day, month and year while the custom format string dd MMM yyyy uses space . As long as there is even a single difference in the way I have stored date time string value in item variable which is not complying with the custom format string ddd dd MMM yyyy h:mm tt it will burst. The moment I make the value of item to Sun 22 May 2016 3:52 AM it succeeds. You just change the value of item.Date in the object of MailDetailDTO object to match it with the custom date time string format to get rid of the error OR change the custom date time format string that you are passing to the PraseExact API to match it with the format of date time value coming in item.Date from your back-end data.

mono: DateTimeOffset.TryParseExact works on full .NET but not on debian

My C# project is taking xml and extracting pertinent data, one of which pieces is a date time value. The following code works correctly on my desktop running Win8.1 and .NET4. However when I run it through mono, it's failing to parse the data.
using glob = System.Globalization;
DateTimeOffset dt = DateTimeOffset.MinDate;
string[] fmts = new string[]
{
"MMM dd, yyyy hh:mm tt EDT",
"MMM dd, yyyy hh:mm tt EST",
"MMM dd, yyyy hh:mm tt CDT",
"MMM dd, yyyy hh:mm tt CST",
"MMM dd, yyyy hh:mm tt MDT",
"MMM dd, yyyy hh:mm tt MST",
"MMM dd, yyyy hh:mm tt AKST",
"MMM dd, yyyy hh:mm tt AKDT",
"MMM dd, yyyy hh:mm tt HST",
"MMM dd, yyyy hh:mm tt PST",
"MMM dd, yyyy hh:mm tt PDT"
};
var dtString = z.Substring(pos1 + 5, pos2 - pos1 - 1 - 5).Replace("ft", "").Trim();
dtString = dtString.Substring(0, 1).ToUpper() + dtString.Substring(1);
dtString = dtString.Substring(0, dtString.Length - 7)
+ dtString.Substring(dtString.Length - 7).ToUpper();
DateTimeOffset.TryParseExact(dtString, fmts,
glob.CultureInfo.InvariantCulture, glob.DateTimeStyles.None, out dt);
To check if the conversion worked ok, I do this:
if (dt == DateTimeOffset.MinDate)
Console.WriteLine("failed to convert dt = MinValue -> " + dtString);
Here's an example of the data string being processed:
raw: mar 21, 2015 10:30 am cdt
after my formatting: Mar 21, 2015 10:15 AM CDT
It's not specific to the CDT tz - I get the same issue for all timezones.
When I run $ date on the Linux box, it's reporting the same date, time and tz as my desktop, in this format (Mon Mar 23 11:31:16 EDT 2015).
The section is wrapped in a try/catch, but no exceptions are being thrown (also have Console output in there).
I can code around it by changing the string around before TryParse, but it would seem this method was designed so that this is not necessary.
Is this a bug (or am I missing something)? If so where does one report them?
Thanks
A few points:
In the code you posted, the part where you manipulate the dtString variable is meaningless to us, because you didn't include values for pos1 or pos2. It seems quite messy, and in general - that sort of manipulation should be avoided if possible. I'm not sure what it has to do with your question, if anything.
You are using the TryParseExact method, which returns a boolean true on success - so the comparison check is unnecessary. (Also, the field is called MinValue, not MinDate)
Time zone abbreviations are not valid in format strings. The letters in the string could be confused with actual custom formatting values. If you wanted to exclude them, you would place them in single-tick or double-tick quotation marks.
In general, time zone abbreviations should not be used for input. There are just too many ambiguities. For example, this list of abbreviations shows 5 possible interpretations of "CST".
The parsers that come with the DateTime and DateTimeOffset types do not understand time zone abbreviations at all. You claim it works fine on your desktop under .NET 4, but I call BS.
As you can see, it did not interpret the offset as CDT (-05:00). Instead it took the local time zone from my computer, which happens to be PDT (-07:00).
The correct way to deal with this is to parse the date input as a DateTime, then use some other mechanism to determine the offset. If you MUST use the time zone abbreviation, and you are absolutely sure you only have the time zones you showed above, and they're all from the united states, then it would go something like this:
// define the list that you care about
private static readonly Dictionary<string, TimeSpan> Abbreviations = new Dictionary<string, TimeSpan>
{
{"EDT", TimeSpan.FromHours(-4)},
{"EST", TimeSpan.FromHours(-5)},
{"CDT", TimeSpan.FromHours(-5)},
{"CST", TimeSpan.FromHours(-6)},
{"MDT", TimeSpan.FromHours(-6)},
{"MST", TimeSpan.FromHours(-7)},
{"PDT", TimeSpan.FromHours(-7)},
{"PST", TimeSpan.FromHours(-8)},
{"AKDT", TimeSpan.FromHours(-8)},
{"AKST", TimeSpan.FromHours(-9)},
{"HST", TimeSpan.FromHours(-10)}
};
static DateTimeOffset ParseInput(string input)
{
// get just the datetime part, without the abbreviation
string dateTimePart = input.Substring(0, input.LastIndexOf(" ", StringComparison.Ordinal));
// parse it to a datetime
DateTime dt;
bool success = DateTime.TryParseExact(dateTimePart, "MMM dd, yyyy hh:mm tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
// handle bad input
if (!success)
{
throw new ArgumentException("Invalid input string.", "input");
}
// get the abbreviation from the input string
string abbreviation = input.Substring(input.LastIndexOf(" ", StringComparison.Ordinal) + 1)
.ToUpperInvariant();
// look up the offset from the abbreviation
TimeSpan offset;
success = Abbreviations.TryGetValue(abbreviation, out offset);
if (!success)
{
throw new ArgumentException("Unknown time zone abbreviation.", "input");
}
// apply the offset to the datetime, and return
return new DateTimeOffset(dt, offset);
}
Now it will return the correct output:
string dtString = "Mar 21, 2015 10:15 AM CDT";
DateTimeOffset dto = ParseInput(dtString);
Console.WriteLine(dto);
Also note that if you were really trying to cover all legal US time zones, you should also consider adding HAST, HADT, CHST, SST, and AST to the list.

Display date time with hours and minutes

I am trying to display date time as follows Wednesday, 05 May 2014 21:25
I tried the following but when using ToLongDateString I am not getting time, this is my code
DateTime date = DateTime.Now;
string formattedDate = date.ToLongDateString();
string fDate = date.ToString("MMMM dd, yyyy,H:mm");
Response.Write(formattedDate);
Date string does not include time. That's why it called date string. Here is your desired format:
DateTime date = DateTime.Now;
string formattedDate = date.ToString("dddd, dd MMMM yyyy HH:mm");
// Wednesday, 07 May 2014 12:05
ToLongDateString does not contain the time, as the time is not part of the date.
See HERE for some details:
Current culture: "en-US"
Long date pattern: "dddd, MMMM dd, yyyy" Long date string:
"Wednesday, May 16, 2001"
Long time pattern: "h:mm:ss tt" Long time string: "3:02:15 AM"
Short date pattern: "M/d/yyyy" Short date string: "5/16/2001"
Short time pattern: "h:mm tt" Short time string: "3:02 AM"
Also HERE and HERE on all the possiblities with ToString for DateTime.
You possibly want to use ToString("F"):
The "F" standard format specifier represents a custom date and time
format string that is defined by the current
DateTimeFormatInfo.FullDateTimePattern property. For example, the
custom format string for the invariant culture is "dddd, dd MMMM yyyy
HH:mm:ss".
You need to use the string dddd, dd MMM yyyy HH:mm.
string fDate = DateTime.Now.ToString("ddddd, dd MMMM yyyy HH:mm");
Response.Write(fDate );
Also, your code is outputting formattedDate not the fDate value.
try this way
DateTime time = DateTime.Now; // Use current time
string format = "dddd, d MMM yyyy HH:mm"; // Use this format
Console.WriteLine(time.ToString(format)); // Write to console
for more details visit below page
http://www.dotnetperls.com/datetime-format
Your can try this
DateTime date = DateTime.Now;
string formattedDate = date.ToLongDateString();
string fDate = date.ToString("dddd MMMM dd, yyyy hh:mm");
Response.Write(fDate);
This format should work:
DateTime date = DateTime.Now;
string formattedDate = date.ToString("f");
// January 13, 2023 5:00 PM
Personally, I like the format that just doing ToString() gives me e.g
HelperLib.LogMsg("Job Ran at + " + DateTime.Now.ToString();
// Job Ran at 21/01/2023 21:12:59
You can change the format with hh:mm if you don't want seconds as people have shown you above, however this format is exactly what I want and need. If I wanted the day name or month name I would use the formatting people have shown you above but for mew this gives me the Date and time and any variable that is a date format it works on e.g
DateTime raceDateTime = Convert.ToDateTime(RecordsetRow["RaceDateTime"]);
Console.WriteLine("racedatetime = " + raceDateTime.ToString();
and the same output...
The following should work:
string formattedDate = date.ToLongDateString();
formattedDate += date.ToString(" h:mm");

DateTime TryParseExact a string containing a 3 letter month

I am writing an extension method to parse a specific string which contains a date and a time into a DateTime object using the DateTime.TryParseExact() Method.
An example of the format is as follows:
"29 November 2013 20:04"
The code I am using to parse it to a DateTime is:
public static DateTime MyToDateTime(this string value)
{
DateTime converted;
DateTime.TryParseExact(value, "dd MMM yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
return converted;
}
The result is always DateTime.Min (i.e 0001-01-01 00:00:00.000)
I cant figure out what is wrong with my format string. Any help would be appreciated.
from your comments:
if you want to parse 3 Letter Month use MMM.
if you want to parse 24-Hour format you should use HH instead of hh.
Try This:
DateTime.TryParseExact(value, "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
There are two problems I see:
November is not a 3-letter month—that would be Nov. To parse a full date name, use MMMM.
To parse a 24-hour time use HH.
This should work:
DateTime.TryParseExact(value, "dd MMMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
Further Reading
Custom Date and Time Format Strings
Try adding an extra M and a capital H
DateTime.TryParseExact(value, "dd MMMM yyyy H:mm", .....
See here for more info: How can I visualize the way various DateTime formats will display?
MMM stands for the abbreviated name of the month, so it's not what you're looking fore. Use MMMM instead.
Find all custom Date and Time format string on MSDN: Custom Date and Time Format Strings.
You should also check the value returned by TryParseExact method. It returns false when parse failed and true when it was performed without any problems.
And hh should be HH to parse hour part of your input.

C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy

How to convert "yyyy-MM-ddTHH:mm:ss" into "dd MMM yyyy" format? For Instance, i want to convert 2013-04-16 05:30:05 into 16 April 2013. What is the correct method to achieve this?
First ParseExact then do ToString (I assume that you have string object, if you have DateTime object, skip first line)
var dateTime = DateTime.ParseExact(yourDateString, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
var yourNewString = dateTime.ToString("dd MMM yyyy");
Note that representation of DateTime you see in debugger is dependant on your current culture.
First, a DateTime has no format. But if you've already a string that represents a DateTime with the format yyyy-MM-ddTHH:mm:ss and you want to convert it to a string-date with format dd MMM yyyy you need to parse it to DateTime first.
Therefore use DateTime.ParseExact:
DateTime dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
Now you can use DateTime.ToString:
string result = dt.ToString("dd MMM yyyy");
Note that you need to pass a different CultureInfo object to ParseExact/ToString if you want to parse with another DateTimeFormat than your current (f.e. force english month names instead of german: dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)).
As others mentioned, a DateTime has no format. To parse a string literal to a Date you need to call DateTime.Parse (if the string is in a culture-specific format) or DateTime.ParseExact if you need to pass a format string.
The format can be a custom format like yyyy-MM-dd HH:mm:ss or one of the standard format strings, eg. s for yyyy-MM-ddTHH:mm:ss.
2013-04-16 05:30:05 it not in one of the standard formats, so you have to parse by passing a custom format string:
var dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
On the other hand, yyyy-MM-ddTHH:mm:ss is the s standard format so you can just write:
var dt = DateTime.ParseExact("2013-04-16T05:30:05", "s", null);

Categories

Resources