Trying to get a character out of a string but it displays error
"Index and length must refer to a location within the string"
here is my sample code below, the error part occurs in the "timeOnly"
string sampleDate = "2020-09-16T05:32:38+8:00";
string dateOnly = sampleDate.Substring(0, 10).ToString();
string timeOnly = sampleDate.Substring(12, 18).ToString();
string finalDate = dateOnly + " " + timeOnly;
How do i get the time only of sampleDate and get only 05:32:38 out of the string
How to get the MIDDLE characters of string?
In short, you don't
What you have is a DateTime not just a regular string. The most reliable and sane way to treat it is by parsing it as a DateTime, or DateTimeOffset. Since you don't want the timezone information you can use the later and format it however you like
string sampleDate = "2020-09-16T05:32:38+8:00";
var asd = DateTimeOffset.Parse(sampleDate);
Console.WriteLine(asd.TimeOfDay.ToString());
If you need the Timezone information in the future, you might want to use DateTime.Parse. This all gives you the ability to treat the Date Time / Time as such if and when you need it, with the standard formatting features and cultural tools needed when dealing with such constructs
Output
05:32:38
Full Demo Here
The second parameter to the Substring method is the length you want, not the end index. And the first parameter is also wrong in your second call.
So, change to this:
string sampleDate = "2020-09-16T05:32:38+8:00";
string dateOnly = sampleDate.Substring(0, 10).ToString();
string timeOnly = sampleDate.Substring(11, 8).ToString();
string finalDate = dateOnly + " " + timeOnly;
A couple more tips. You don't need to write the variable type when it can be inferred. And Substring already returns a string, so no need to call ToString.
var sampleDateString = "2020-09-16T05:32:38+8:00";
var dateOnly = sampleDate.Substring(0, 10);
var timeOnly = sampleDate.Substring(11, 8);
var finalDate = dateOnly + " " + timeOnly;
only change the range, for example :
string timeOnly = sampleDate.Substring(11, 8).ToString();
result:05:32:38
I need to process the CreationTime I retrieve from the PDF's metadata and compare it to DataTime format.
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
This returns a Date-Time-String like:
D:20150710080410
D:20150209075651+01'00'
and to compare:
DateTime Created = Convert.ToDateTime(CreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
Martin
I really needed a solution for this, BBL Admin 's Comment on writing your own function turned out to be my way out.
From this [this itex support link][1] I was able to get the intepratation of the pdfDate format as D:YYYYMMDDHHmmSSOHH'mm'
Next thing I needed to know is the supportade date formats in c# that I may Parse using DateTime.Parse() from [this c-sharpcorner artical][2] and the most ideal for me was "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss"
Having known the input I get and the format I can parse, I created the function below to construct the date, basically getting parts from the pdfDate and building parts for the 'parsable' date string...
private DateTime CreateDateTime(string date) //use the pdfDate as parameter to the date argument
{
string dateStr = date.Remove(0, 2).Remove(14, 6); //Remove D: & OHH'mm
string tmpDateStr = dateStr.Substring(0, 4) //Get year i.e yyyy
+ "-" + dateStr.Substring(4, 2) // Get month i.e mm & prepend - (hyphen)
+ "-" + dateStr.Substring(6, 2) // Get day i.e dd & prepend -
+ "T" + dateStr.Substring(8, 2) // Get hour and prepend T
+ ":" + dateStr.Substring(10, 2) // Get minutes and prepend :
+ ":" + dateStr.Substring(12, 2); //Get seconds and prepend :
return DateTime.Parse(tmpDateStr);
}
Well, I hope you found a way at the time of asking, anyone else facing the same challange could try my approach and see if it helps. Nevertheless, question answered.
NB: There could be other/better ways to do it.
[1]: http://itextsupport.com/apidocs/iText7/7.1.0/com/itextpdf/kernel/pdf/PdfDate.html
[2]: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
If your Date-Time string that you're trying to convert is going to start with "D:" every time, then you might think about adding in a remove function for D:. That's what's probably giving you the exception when you try to convert. Try this:
// Gather the Info
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
string sCreatedDate = Convert.ToString(CreatedDate).Remove(0, 2)
// Convert and Compare
DateTime Created = Convert.ToDateTime(sCreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
You don't have to create sCreatedDate, but it's a little bit cleaner to view it that way. You could also convert CreatedDate.ToString().Remove(0,2) when you do the datetime convert:
DateTime Created = Convert.ToDateTime(CreatedDate.ToString().Remove(0,2));
Hope this helps.
I tried to enter the date of the current day with the following code:
string now = (DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year).ToString();
string tm = (DateTime.Today.Hour + ":" + DateTime.Today.Minute).ToString();
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod,des, now );
Dal.DoQuery(sql2);
when I run this code it shows me the error in the title :
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value
How do I solve it?
------------------edit
i changed it to:string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss"); and it works.
now i have another problem, when i run the code below it shows me the error:Error converting data type varchar to numeric.
string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss");
string tm = DateTime.Now.ToString("HH:mm:ss");
string sql = string.Format("INSERT INTO Kabala1 (Nu_kabala,Ma_num,Date,Time,Total,Status,Name,User_n) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", n, Session["Ma_num"], now, tm, lprice, "ddffs", Session["user"], "ddffs");
Dal.DoQuery(sql);
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod, des, now);
Dal.DoQuery(sql2);
string sql3 = string.Format("INSERT INTO Kabala3 ((Nu_kabala,Msd,Ma_num,Kind_pay,Name_pay,Date_pay,Sk,Ms_sek,Snif,Bank,Date_klita,Seif) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", n,"1", Session["Ma_num"],"13", "ddffds", now, lprice, this.card.Text, this.mm.Text, this.yy.Text, now, lkod);
Dal.DoQuery(sql3);
You can Use DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss") //Whatever format...
or Use direct sql instead using CONVERT method. Syntax is
in your case, use the 103 format for the date
CONVERT(VARCHAR,DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year,103)
and 108 for the time
CONVERT(VARCHAR, DateTime.Today.Hour + ":" + DateTime.Today.Minute + ":00" ,108)
whould give format of hh:mm:ss
full reference from the following w3 link:
http://www.w3schools.com/sql/func_convert.asp
The standard form for dates in MySQL is YYYY-MM-DD. I would suggest using this format. Perhaps this will create the string in the right format:
string now = (DateTime.Today.Year + "-" + DateTime.Today.Month + "-" + DateTime.Today.Year).ToString();
Just Change the date settings in your computer or lap. I hope you know how its is done !
If you don't...
choose your calendar from right bottom.
then choose change date and time settings
then choose change date and time
then choose change calendar settings
then in date formats> change short date as either MM/dd/yyyy or dd/MM/yyyy. Choose which is right for your computer. For me it was MM/dd/yyyy.
The following code:
string s = DateTime.Now.ToString();
DateTime dt;
DateTime.TryParse(s, out dt);
textBox1.AppendText(s + "\n");
textBox1.AppendText(DateTime.Now + "\n");
textBox1.AppendText(dt.ToString() + "\n");
DateTime.TryParse(s,
CultureInfo.CurrentCulture.DateTimeFormat,
DateTimeStyles.None,
out dt);
textBox1.AppendText(dt.ToString() + "\n");
produces the following output on the textbox:
13.09.2013 1602.38
13.09.2013 1602.38
01.01.0001 0000.00
01.01.0001 0000.00
Why TryParse can't parse the string s to correct DateTime object? I want my program to be able to correctly parse the strings formatted like s. How can I do that?
This is a C# WPF program running on .NET Framework 4.
It appears your DateSeperator and TimeSeperator are same. In this case it is .
While converting DateTime to string framework just places . in place of those seperators so converting to string works smooth.
But when parsing it back to DateTime when datetime parser finds . character It doesn't have any clue in finding whether the element is Date part or Time part. and hence it fails.
Here is the snippet reproducing the issue and shows the fix.
CultureInfo c = new CultureInfo("en-us", true);
c.DateTimeFormat.DateSeparator = ".";
//c.DateTimeFormat.TimeSeparator= ".";//this will fail
c.DateTimeFormat.TimeSeparator= ":";//this will work since TimeSeparator and DateSeparator are different.
Thread.CurrentThread.CurrentCulture = c;
string s = DateTime.Now.ToString();
DateTime dt;
DateTime.TryParse(s, out dt);
Console.WriteLine(s + "\n");
Console.WriteLine(DateTime.Now + "\n");
Console.WriteLine(dt.ToString() + "\n");
DateTime.TryParse(s,
CultureInfo.CurrentCulture.DateTimeFormat,
DateTimeStyles.None,
out dt);
Console.WriteLine(dt.ToString() + "\n");
Conclusion:
You should not set DateTimeFormat and TimeSeparator to the same value. Doing so gives trouble for the runtime in parsing DateTime so it fails. :)
string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
//MessageBox.Show(temp);
temp = temp[0].ToString() + temp[1].ToString() + temp[2].ToString() + temp[3].ToString() +
temp[4].ToString() + temp[5].ToString() + temp[6].ToString() + temp[7].ToString() +
temp[8].ToString() + temp[9].ToString();//converting to dd-MM-yyyy
labeldate = DateTime.ParseExact(temp,"dd-MM-yyyy",
CultureInfo.InvariantCulture);
I use the above code to convert string (dd/mm/yyyy format) into datetime type. It works fine on my computer. But the same gives an error on other computers saying string was not recognized as datetime. On further investigation. I saw that in other computers temp showed 1/1/2013 or 11/3/2013 whereas on mine it would show 01-01-2013 or 11-03-2013. I can't seem to solve this. Any help?
This is likely a culture issue. Use .ToString(CultureInfo.InvarientCulture) and you'll get the same result regardless of the culture set on the computer.
If all you are doing is trying to get the date portion of the date time you can simplify your code to
string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
labeldate = DateTime.Parse(temp).Date;
As for the culture problem wilsjd mentioned. If ToolTipText is using the default culture rules for however that text is being entered the parser should use the same rule when it tries to parse it back out.