I have 2 strings (date(13/04/2021),time("06:30")) and I want to combine them together to datetime format and I am getting the below error.
System.FormatException: 'String was not recognized as a valid DateTime.'
What I am doing wrong?
if I change the tempdate format to "yyyy-dd-MM" I get the error there
var type = form["GymType"];
var time = form["states_ddl"];
var date = form["date2"];
var username = form["username"];
var numberofpersons = 0;
if (type == "2")
{
//gym
numberofpersons = 9;
}
else
{
//cross
numberofpersons = 5;
}
Booking toadd = new Booking();
var currenduser = User.Identity.GetUserId();
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(tempdate + " " + time, "yyyy-dd-MM HH:mm", CultureInfo.InvariantCulture);
What you do is convert de string to a dateTime 'tempdate', and than on the next line you convert it back to a string.
What i would do is convert the date as you do and parse the time separate, than add them together.
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
var timspan = TimeSpan.Parse(time);
DateTime d = tempdate.Add(timspan);
You can use Convert to do this
var date = Convert.ToDateTime("13/04/2021 06:30");
try this
string d = "13/04/2021";
string t = "10:30PM";
string dateAndTime = d.Trim() + ' ' + t.Trim();
DateTime dt = DateTime.ParseExact(dateAndTime, "MM/dd/yyyy hh:mmtt",
CultureInfo.InvariantCulture, DateTimeStyles.None);
dt = DateTime.Parse(dateAndTime, CultureInfo.InvariantCulture,
DateTimeStyles.None);
Related
I tried to convert dd/MM/yy to dd/MM/yyyy using this code:
int i = 0;
string d = "";
foreach(DataRow dr in dataset.Tables["FinData"].Rows)
{
d = DateTime.ParseExact(dr["Date"], "dd/MM/yy", CultureInfo.InvariantCulture);
dataset.Tables[0].Rows[i]["date"] = d;
i++;
}
but it seems I have a problem with datetime.parseexact usage.
How can modify it?
Here is the full coding:
DateTimeFormatInfo formatProvider = new DateTimeFormatInfo();
formatProvider.Calendar.TwoDigitYearMax = DateTime.Now.Year;
label1.Text = fbd.SelectedPath;
Uri url = new Uri(#"http://www.google.com/finance/historical?q=KRX%3A005930&ei=-gUcWcG4Aom_0AS2sKyoBg&start=30&num=30&output=csv");
wc.DownloadFile(url, label1.Text + #"\finance.csv");
FileStream fs = new FileStream(label1.Text + #"\finance.csv", FileMode.Open);
StreamReader sr = new StreamReader(fs);
DataSet dataset = new DataSet();
dataset.Tables.Add("FinData");
dataset.Tables["FinData"].Columns.Add("Date");
dataset.Tables["FinData"].Columns.Add("Open");
dataset.Tables["FinData"].Columns.Add("High");
dataset.Tables["FinData"].Columns.Add("Low");
dataset.Tables["FinData"].Columns.Add("Close");
dataset.Tables["FinData"].Columns.Add("Volume");
string item;
while ((item = sr.ReadLine()) != null)
{
myArr = item.Split(',');
dataset.Tables["FinData"].Rows.Add(myArr);
}
int i = 0;
string d = "";
foreach(DataRow dr in dataset.Tables["FinData"].Rows)
{
d = DateTime.ParseExact(dr["Date"], "dd/MM/yy", CultureInfo.InvariantCulture);
dataset.Tables[0].Rows[i]["date"] = d;
i++;
}
You can use the ToFourDigitYear method to convert YY to YYYY
string strDate = "31/12/17";
System.Globalization.GregorianCalendar gregCal = new System.Globalization.GregorianCalendar();
DateTime dtDate = new DateTime(gregCal.ToFourDigitYear(Convert.ToInt32(strDate.Substring(6, 2))), Convert.ToInt32(strDate.Substring(3, 2)), Convert.ToInt32(strDate.Substring(0, 2)));
Use
Convert.ToDateTime(dataset.Tables[0].Rows[i]["DATE"]).ToString("dd/MM/yyyy");
It seems to me that there is already an answer here:Convert datatable date into dd/mm/yyyy format in asp.net
Your csv file (of which you kindly provided the semi-encrypted link) contains dates like "28-Mar-17". Even if DateTime.ParseExact is new to you, it shouldn't be hard to infer from its name that it parses a date string exactly according to the given format, which isn't "dd/MM/yy". So this is how to use it:
d = DateTime.ParseExact(dr["Date"], "dd-MMM-yy", CultureInfo.InvariantCulture);
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 have a string which is not in a datetime format eg:20160503. How can i change it to Datetime. I tried using Substring. It is working.Is there any more efficient way? Below is what I have right now.
string a = "20160503";
int b = Convert.ToInt32(a.Substring(0, 4));
int c = Convert.ToInt32(a.Substring(4, 2));
int d = Convert.ToInt32(a.Substring(6, 2));
string date = b + "/" + c + "/" + d;
DateTime result = new DateTime();
DateTime.TryParse(date, out result);
Since you know the exact format of your datetime, you could try to use the ParseExact DateTime's method.
var dt = DateTime.ParseExact(a,"yyyyMMdd",CultureInfo.InvariantCulture);
For further info, please have a look here.
Try somthing like this:
Define your own parse format string to use.
string formatString = "yyyyMMdd";
string sample = "20160503";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
Thanks for your replies. Finaly I ended up using DateTime.TryParseExact
string dateString = "20150503";
DateTime dateValue = new DateTime();
DateTime.TryParseExact(dateString, "yyyyMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);
I need to convert a string format dd/mm/yy to a datetime.
I tried with:
DateTime d;
if (DateTime.TryParseExact(dateStr.Trim(), "dd/MM/yyyy", new CultureInfo("es-es"), DateTimeStyles.AssumeLocal, out d))
return d;
Your code seems ok, but also you can convert a string into datetime like below
DateTime d = DateTime.ParseExact("11/02/2016", "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d;
if you have string as dd/MM/yy format and need to convert it as dd/MM/yyyy fomat datetime then you can do like this
DateTime temp = DateTime.ParseExact("11/02/16", "dd/MM/yy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(temp.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d
string dateBirth = ddlDay.SelectedItem.ToString() + "/" + ddlMonth.SelectedItem.ToString() + "/" + ddlYear.SelectedItem.ToString();
DateTime dt = DateTime.ParseExact(dateBirth, "dd/MM/yyyy", null);