Convert string with long month name to DateTime - c#

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);

Related

Converting a DateTime format

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);

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");

Convert date time format?

I am trying to convert date time in 12/20/2013 17:40 format to the below format
20 Dec 2013 05:40 pm. How it's possible?
You need to use DateTime.TryParseExact. This should do it
string originalDate = "2/20/2013 17:40";
DateTime parsedDate;
if (DateTime.TryParseExact(originalDate, "M/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
{
string requiredFormat = parsedDate.ToString("dd MMM yyyy hh:mm ttt");
}
OutPut:
20 Feb 2013 05:40 PM
mydatetime.ToString("dd MMM yyyy hh:mm tt");
dt.ToString("dd MMM yyyy hh:mm tt");
dateTime.ToString("dd MMM yyyy hh:mm tt");
Method 1: if you have datetime in String format
String str = "12/20/2013 17:40";//20 Dec 2013 05:40 pm
DateTime result;
string date="";
if (DateTime.TryParseExact(str, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
date=result.ToString("dd MMM yyyy hh:mm tt");
Method 2: if you have datetime in DateTime variable.
String strdatetime=datetime.ToString("dd MMM yyyy hh:mm tt");
DateTime time = DateTime.Now;
Console.WriteLine(time.ToString("dd MMM yyyy hh:mm tt"));
You can use format strings:
this is from 1 minute google:
http://www.csharp-examples.net/string-format-datetime/
http://www.dotnetperls.com/datetime-format
First of all, DateTime doesn't have a format, strings have..
If your 12/20/2013 17:40 is a DateTime, you can use DateTime.ToString(String, IFormatProvider) method to format it like;
date.ToString("dd MMM yyyy hh:mm tt", CultureInfo.InvariantCulture);
If your 12/20/2013 17:40 is a string, then you can use DateTime.ParseExact(String, String, IFormatProvider) method like;
string s = "12/20/2013 17:40";
var date = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("dd MMM yyyy hh:mm tt", CultureInfo.InvariantCulture));
Output will be;
20 Dec 2013 05:40 PM
Here a demonstration.
For more information, take a look at;
Custom Date and Time Format Strings
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime date = DateTime.Parse("12/20/2013 17:40");
string formattedDate = $"{date: dd MMM yyyy hh:mm tt}";

String was not recognized as a valid DateTime

DateTime dtEndTime = DateTime.ParseExact(
appToDate,
timeFormats,
null,
System.Globalization.DateTimeStyles.None);
appToDate = 21-02-2013 12:30 AM
string[] timeFormats = {
"dd-MM-yyyy H:m tt",
"dd-MM-yyyy H:mm tt",
"dd-MM-yyyy HH:m tt",
"dd-MM-yyyy HH:mm tt"
};
String was not recognized as a valid DateTime.
I suspect the problem is your use of H combined with tt. H and HH indicate an hour in the range 0-23, where 12 is noon, and therefore PM.
I suspect you want h and hh instead of H... although you shouldn't need every combination of h/H/m/mm. (Do you really expect to see "1:5 PM"?) I suspect just "dd-MM-yyyy H:mm tt" should cover you.

How do I convert Paypal's HH:MM:SS DD Mmm(.) YYYY PST/PDT to a C# UTC DateTime?

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.

Categories

Resources