I have two string variables. The first one is from a label (This date will be subject to changed dependant on a datetimepicker). The second one is a time that is selected in a combo box. The format is in this example -
lblActualDate.Text - 11 June 2015
comboStartTime.Text - 12.00AM
I am getting errors about the strings not being in the correct format to convert to date time.
My aim is to make an instance with the values from a form
Here is my code -
private void btnSave_Click(object sender, EventArgs e)
{
string dateString = lblActualDate.Text + " " + comboStartTime.SelectedItem;
DateTime startTime = DateTime.ParseExact(dateString, "dd MMMM yyyy hh.mmtt", CultureInfo.InvariantCulture);
int length = int.Parse(comboLength.SelectedText);
string description = txtBoxSubject.Text;
string location = txtBoxLocation.Text;
Appointment newAppointment = new Appointment(startTime, length, description, location);
Appointments appointments = new Appointments();
appointments.Add(newAppointment);
appointments.Save();
txtBoxLocation.Clear();
txtBoxSubject.Clear();
Dispose();
}
Convert.ToDateTime uses standard date and time formats of your CurrentCulture. That means your string format doesn't match one of these formats.
You can use custom date and time formats to parse your string like;
string s = "11 June 201512.00AM";
DateTime startTime = DateTime.ParseExact(s, "dd MMMM yyyyhh.mmtt",
CultureInfo.InvariantCulture);
Also consider to put a white space between your date and time part.
Most likely you've got some combinations with one digit, and others with two digits in either the day or hour portions of your date/time.
You can allow all the possibilities by building up an array of allowable formats and passing that to ParseExact:
string[] formats = { "d MMMM yyyy h.mmtt", "d MMMM yyyy hh.mmtt", "dd MMMM yyyy h.mmtt", "dd MMMM yyyy hh.mmtt" };
DateTime startTime = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Related
I have this string July 1, 2021 9:10 AM and I'm trying to parse it into a DateTime variable.
This isn't working for me. ST is a variable that has the string representation of the date and time.
var Event = DateTime.ParseExact(ST, "MMMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);
You are using the wrong day format. For a month day without a leading zero, you should use the following:
var Event = DateTime.ParseExact(ST, "MMMM d, yyyy h:mm tt", CultureInfo.InvariantCulture);
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.
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.
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");
I would like to log a payment_date in this format in a SQL Server database.
Update. Instinct was right on this one. Found a solution here: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html, verifying... of course, if Paypal ever moves out of the West Coast, I'll be in trouble. Is there a better way to parse this? Maybe with TimeZone?
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// convert to local timezone
outputDateTime = outputDateTime.AddHours(3);
return outputDateTime;
}
Wait a sec, that code above is completely wrong for me. I'm on the West Coast! Ideally this should be updated to send the date to a proper UTC DateTime and handle any time zone. Also the code above doesn't handle PDT properly (if converted to UTC).
Update2. Apparently, at least in previous versions, the sandbox would return "Feb." while the live returns "Feb". Lol. Someone save me!
Update3. Link to Regex version http://www.ifinity.com.au/Blog/EntryId/77/Converting-PayPal-Dates-to-Net-DateTime-using-Regex, but debugging could be an issue. Regex does not seem like the right way to do this. There must be a better way.
/// <summary>
/// Converts a PayPal datestring into a valid .net datetime value
/// </summary>
/// <param name="dateValue">a string containing a PayPal date</param>
/// <param name="localUtcOffset">the number of hours from UTC/GMT the local
/// time is (ie, the timezone where the computer is)</param>
/// <returns>Valid DateTime value if successful, DateTime.MinDate if not</returns>
private static DateTime ConvertFromPayPalDate(string rawPayPalDate, int localUtcOffset)
{
/* regex pattern splits paypal date into
* time : hh:mm:ss
* date : Mmm dd yyyy
* timezone : PST/PDT
*/
const string payPalDateRegex = #"(?<time>\d{1,2}:\d{2}:\d{2})\s(?<date>(?<
Mmm>[A-Za-z\.]{3,5})\s(?<dd>\d{1,2}),?\s(?<yyyy>\d{4}))\s(?<tz>[A-Z]{0,3})";
//!important : above line broken over two lines for formatting - rejoin in code editor
//example 05:49:56 Oct. 18, 2009 PDT
// 20:48:22 Dec 25, 2009 PST
Match dateMatch = Regex.Match(rawPayPalDate, payPalDateRegex, RegexOptions.IgnoreCase);
DateTime time, date = DateTime.MinValue;
//check to see if the regex pattern matched the supplied string
if (dateMatch.Success)
{
//extract the relevant parts of the date from regex match groups
string rawDate = dateMatch.Groups["date"].Value;
string rawTime = dateMatch.Groups["time"].Value;
string tz = dateMatch.Groups["tz"].Value;
//create date and time values
if (DateTime.TryParse(rawTime, out time) && DateTime.TryParse(rawDate, out date))
{
//add the time to the date value to get the datetime value
date = date.Add(new TimeSpan(time.Hour, time.Minute, time.Second));
//adjust for the pdt timezone. Pass 0 to localUtcOffset to get UTC/GMT
int offset = localUtcOffset + 7; //pdt = utc-7, pst = utc-8
if (tz == "PDT")//pacific daylight time
date = date.AddHours(offset);
else //pacific standard time
date = date.AddHours(offset + 1);
}
}
return date;
}
I haven't done any C# since 2006, so this code probably doesn't compile. Test it before you fly!
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// Get the offset.
// If C# supports switching on strings, it's probably more sensible to do that.
int offset;
if (payPalDateTime.EndsWith(" PDT"))
{
offset = 7;
}
else if (payPalDateTime.EndsWith(" PST"))
{
offset = 8;
}
else
{
throw some exception;
}
// We've "parsed" the time zone, so remove it from the string.
payPalDatetime = payPalDateTime.Substring(0,payPalDateTime.Length-4);
// Same formats as above, but with PST/PDT removed.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy", "HH:mm:ss MMM. dd, yyyy" };
// Parse the date. Throw an exception if it fails.
DateTime ret = DateTime.ParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// Add the offset, and make it a universal time.
return ret.AddHours(offset).SpecifyKind(DateTimeKind.Universal);
}
This should work
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
CultureInfo enUS = new CultureInfo("en-US");
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT",
"HH:mm:ss dd MMM yyyy PST", "HH:mm:ss dd MMM. yyyy PST", "HH:mm:ss dd MMM yyyy PDT", "HH:mm:ss dd MMM. yyyy PDT"};
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out outputDateTime);
// convert to local timezone
TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
outputDateTime = TimeZoneInfo.ConvertTime(outputDateTime, hwZone, TimeZoneInfo.Local);
return outputDateTime;
}
The code in this post seems to work fine: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html
using System;
using System.Globalization;
public static class PayPalTransaction
{
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// convert to local timezone
outputDateTime = outputDateTime.AddHours(3);
return outputDateTime;
}
}
(answer cross-posted for this similar question: How to cast this date and save to database)
Assuming you have already parsed the date with DateTime.ParseExact() (or one of the other similar methods) you can call DateTime.ToUniversalTime()
EDIT: perhaps TimeZoneInfo.ConvertTimeToUtc is more appropriate:
The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.