How can I convert a string representing 12-hour time into a time-only, 24hr format? Here's my code so far.
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
s = String.Format("{0:HH:mm:ss}", ar[0]);
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
DateTime dateTime = DateTime.Parse(ar[0]);
dateTime.ToString("HH:mm");
string s = "7:00 PM";
DateTime dt = Convert.ToDateTime(s);
Console.WriteLine(dt.ToString("HH:mm"));
Try this way
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
s = Convert.ToDatetime(ar[0]).ToString("HH:mm");
Related
I have a date time format of yyyyMMdd:HHmmss. I receive the datetime from a device and I can confirm that the format is yyyyMMdd:HHmmss.
For example I get datetime as 20180331:162308. I tried to convert to 03/31/2018 04:23 PM format by using below code:
string localDateTime =
Convert.ToString(protocol.GetParameter(Parameter.localmdmdatetimestr_3043));
string formatString = "yyyyMMdd:HHmmss";
protocol.Log(
"QA" + protocol.QActionID + "|DateTime|localDateTime" + localDateTime,
LogType.Error,
LogLevel.NoLogging);
DateTime LocalDt = DateTime.ParseExact(
localDateTime,
formatString,
CultureInfo.InvariantCulture);
But instead get
System.FormatException: String was not recognized as a valid DateTime
error.
As per your requirement
string localDateTime = Convert.ToString("20180331:162308");
string formatString = "yyyyMMdd:HHmmss";
DateTime LocalDt = DateTime.ParseExact(
localDateTime,
formatString, CultureInfo.InvariantCulture);
Console.WriteLine(LocalDt);
var test = LocalDt.ToString("yyyy/MM/dd HH:mm tt", CultureInfo.InvariantCulture);
Console.WriteLine(test);
Console.ReadLine();
I wrote code that could read the date in format dd/mm/yyyy hh:mm AM/PM, but now I need it to read date in the format if mm-dd-yyyy hh:mm Am/PM.
Can someone please guide me in right direction?
My code:
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
foreach (FileInfo fi in fiArray)
{
try
{
StreamReader reader = fi.OpenText();
string date;
string logContent = reader.ReadLine();
string patternDate = "(?<logDate>(\\d){2}-(\\d{2})-(\\d{4})\\s(\\d{2}):(\\d{2})\\s?(?i)(am|pm))";
Regex reg = new Regex(patternDate);
date = reg.Match(logContent).Value.ToString();
// for dt2, the error happens here
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
// DateTime dt2 = DateTime.ParseExact(date, format, provider);
while ((line = reader.ReadLine()) != null)
{
Regex reg1 = new Regex("^(ARCH(?!9{2}))");
bool flag = reg1.IsMatch(line);
if (flag == true)
{
string dt = DateTime.Now.ToString("yyyymmddHHMMss");
string[] values = line.Split(',').Select(sValue => sValue.Trim()).ToArray();
// string uniqueGuid = SequentialGuidGenerator.NewGuid().ToString();
string uniqueGuid = Utility.generateID();
uniqueGuid = uniqueGuid.Replace("-", "").Substring(0,18);
string RPT_ID = values[0].ToString();
RPT_ID = RPT_ID.Remove(0, 4);
table.Rows.Add(uniqueGuid, RPT_ID, values[1].ToString(), dt2);
}
else
{ }
}
reader.Close();
}
catch (MyException e)
{
throw e.MyExceptiona(e, fi);
}
}
Utility.InsertData(table);
This code is reading 01-02-2016 12:40 AM but I need it to read 01-15-2016 12:40 AM
Try like this
DateTime parsedDate ;
string YourDate = "01-15-2016 12:40 AM";
string pattern = "MM-dd-yyyy hh:mm tt";
DateTime.TryParseExact(YourDate, pattern, null,
DateTimeStyles.None, out parsedDate);
how about :
DateTime mydt;
DateTime.TryParseExact("01-16-2016 12:40 AM", "MM-dd-yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out mydt)
For reference about custome datetime parsing : https://msdn.microsoft.com/fr-fr/library/8kb3ddd4(v=vs.110).aspx
I want to convert a datetime to string.
But result now is returned as 04 August, 0016 which is not what I need.
I want result to be 04 August, 2016.
C# code:
DataTable dtGroupCurr = new DataTable();
dtGroupCurr = sourceGroupCurr.Tables[0];
var groupedCurr = (from dt2 in dtGroupCurr.AsEnumerable()
select new
{
S_DATE = dt2.Field<DateTime>("S_DATE"),
BANK_CODE = dt2.Field<string>("BANK_CODE"),
BANK_NAME = dt2.Field<string>("BANK_NAME")
}).Distinct().OrderBy(x => x.S_DATE);
foreach (var s in groupedCurr)
{
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
}
Thanks in advance ;)
Try:
string sDate = s.S_DATE.ToString("dd MMMM, yyyy", new CultureInfo("en-US", true));
Or
string rDate = s.S_DATE.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); // To avoid override
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
The "/" custom format specifier represents the date separator, which
is used to differentiate years, months, and days. The appropriate
localized date separator is retrieved from the
DateTimeFormatInfo.DateSeparator property of the current or specified
culture.
MSDN
Use the DateTime.ParseExact method and specify the format like below:
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.ParseExact(rDate, "yyyy/MM/dd", culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
Use Date or DateTime.ToShortDateString();
Or
Date.ToString("dd-MM-yyyy");
I am getting error String was not recognized as a valid DateTime while converting string to datetime format. I am trying to convert "25-11-2013 06:25:33 PM" to date format. Do any one can help me to solve this issue.
protected void text_changed(object sender, EventArgs e)
{
if (frm.Text == "")
{
Label1.Visible = true;
Label1.Text = "You can leave from textbox blank";
return;
}
string dt = TextBox1.Text;
string amt = dt.ToString();
string ams = amt.ToString() + " " + frm.Text;
DateTime dts = DateTime.ParseExact(ams, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
string ams1 = amt.ToString() + "" + TextBox2.Text;
DateTime dts1 = DateTime.ParseExact(ams1, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
TimeSpan dur = DateTime.Parse(dts1.ToString()).Subtract(DateTime.Parse(dts.ToString()));
double res = 0.0;
res = dur.TotalHours * 20;
TextBox3.Text = res.ToString();
}
If what the user enters is "25-11-2013 06:25:33 PM" then your format string has to be:
string dateFormat = "dd-MM-yyyy hh:mm:ss tt";
The format string you have in your code "MM/dd/yyyy hh:mm:ss tt" requires the user to enter the date as "11/25/2013 06:25:33 PM". All the custom DateTime format string options are described here: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Use a calendar control
You are going to have issues with parsing the dates if you allow users to just enter a free form string. Your best option is to add a calendar control or some other way of structuring the user input so that you don't have to parse a free-form string.
Use the generic converter
Using Convert.ToDateTime will save you a bunch of hassle in setting up the expected formats as it tries it's best to find a date format that will fit. On the other hand you may not get what you expected if the date the user enters can be parsed in multiple ways...
string dts = "09/10/11 06:25";
DateTime dt = System.Convert.ToDateTime(dts);
On my Swedish system it gets converted to 2009-10-11, yy/mm/dd but using a US context the expected date is 2011-09-10, mm/dd/yy.
Use CultureInfo if you can
If you can get the user to indicate or select their culture then parsing date/times from free-form will be much easier - since the user is more likely to enter a culturally correct string.
//this is parsing the datetime using Swedish format
string theCulture = "sv-SE";
string localDts = "2013-11-25 06:25";
DateTime localDt = DateTime.Parse(localDts, System.Globalization.CultureInfo.CreateSpecificCulture(theCulture));
Use an array of format strings
If that isn't possible you should think about the different ways that a user may enter dates and times in your system and add them to an array of supported strings. You may need to add a load of different strings since each format string parses one exact format and the user may enter months,days,hours etc as single digits or omit the seconds part. Here is an example which parses a bunch of different formats, this is in no way complete coverage of all the alternatives...
//A few different strings to test
string dts1 = "25-11-2013 6:25:33";
string dts2 = "11/25/2013 6:25:33";
string dts3 = "25-11-2013 06:25:33";
string dts4 = "11/25/2013 06:25:33";
string dts5 = "25-11-2013 6:25:33 PM";
string dts6 = "11/25/2013 6:25:33 PM";
string dts7 = "25-11-2013 06:25:33 PM";
string dts8 = "11/25/2013 06:25:33 PM";
string dts9 = "25-11-2013 6:5:33 PM";
string dts10 = "11/25/2013 6:5:33 PM";
//The supported datetime formats as an array
string[] dateFormats = {
"dd-MM-yyyy hh:mm:ss tt",
"dd-MM-yyyy h:mm:ss tt",
"dd-MM-yyyy h:m:ss tt",
"dd-MM-yyyy HH:mm:ss",
"dd-MM-yyyy H:mm:ss",
"dd-MM-yyyy H:m:ss",
"MM/dd/yyyy hh:mm:ss tt",
"MM/dd/yyyy h:mm:ss tt",
"MM/dd/yyyy h:m:ss tt",
"MM/dd/yyyy HH:mm:ss",
"MM/dd/yyyy H:mm:ss",
"MM/dd/yyyy H:m:ss"
};
//Parse all the sample strings
DateTime dt1 = DateTime.ParseExact(dts1, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt2 = DateTime.ParseExact(dts2, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt3 = DateTime.ParseExact(dts3, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt4 = DateTime.ParseExact(dts4, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt5 = DateTime.ParseExact(dts5, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt6 = DateTime.ParseExact(dts6, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt7 = DateTime.ParseExact(dts7, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt8 = DateTime.ParseExact(dts8, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt9 = DateTime.ParseExact(dts9, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt10 = DateTime.ParseExact(dts10, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Can i convert the string below to DateTime
Friday, 27th September 2013
This is what i want to achieve:
String tmpDate="Friday, 27th September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
Doing above i get error:
The string was not recognized as a valid DateTime. There is an unknown
word starting at index 10.
Well, I'm not sure there is exactly solution with -th, -st, -nd, but you can use this like;
string tmpDate = "Friday, 27 September 2013";
DateTime dt = DateTime.ParseExact(tmpDate,
"dddd, dd MMMM yyyy",
CultureInfo.InvariantCulture);
Here a DEMO.
I almost suggest you remove -th, -st and -nd part of your string but these are break the rules :)
August
Monday
Thursday
Sunday
Also check Habib's answer which seems nice.
You can maintain the ordinals to remove in an array like this (which might make it easier to add/remove ordinals from other languages). That way you don't have to manually remove the ordinal from each string input. Using TryParseExact avoids an exception being thrown if the DateTime could not be parsed from the string.
String tmpDate = "Friday, 27th September 2013";
string[] split = tmpDate.Split();
string[] ordinals = new string[] { "th", "nd", "st" };
foreach (string ord in ordinals)
split[1] = split[1].Replace(ord, "");
tmpDate = String.Join(" ", split);
DateTime dt;
if(DateTime.TryParseExact(tmpDate, "dddd, dd MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("Parsed");
}
else
{
Console.WriteLine("Could not parse");
}
Your answer is in the exception you are getting. Obviously, "th" is not needed here. Just remove it and you are good to go.
This is working perfectly fine for me
String tmpDate = "Friday, 27 September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
you will have to remove the th, nd,rd and st manually, as there isn't any format that takes these into account. After that you can use try parse exact like below
String tmpDate = "Friday, 27th September 2013";
tmpDate = tmpDate.Replace("nd", "")
.Replace("th", "")
.Replace("rd", "")
.Replace("st", "");
string[] formats = { "dddd, dd MMMM yyyy" };
DateTime dt;
if (DateTime.TryParseExact(tmpDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dt))
{
//parsing is successful
}
Assuming the format of the date string you provide does not change, the -st, -nd and -th can easily be removed (as already suggested).
Also be sure to provide a valid (existing) date, or a System.FormatException will be thrown.
string tmpDate = "Friday, 27th September 2013";
string[] splitDate = tmpDate.Split(new Char[] {' '});
splitDate[1] = splitDate[1].Substring(0, splitDate[1].Length-2);
string tmpDatewithoutStNdTh = String.Join(" ", splitDate);
try{
string closingDate = Convert.ToDateTime(tmpDatewithoutStNdTh).ToString("yyyy-MM-dd");
Console.WriteLine(closingDate.ToString());
}
catch(System.FormatException)
{
Console.WriteLine("The provided date does not exist.");
}
See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}