c# convert PDF metadata CreationTime to DateTime - c#

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.

Related

How to get the middle characters of string that is a Date and Time?

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

Convert 20141013T155544.673-04/0 to DateTime C#

I need to convert
20141013T155544.673-04/0
To a DateTime type.
Presently I am manually parsing the string out
//20130605T154727.683-04/0
//20130806T143808.018-04
//var a = new DateTime();
var year = segmentDate[0].ToString(CultureInfo.InvariantCulture) + segmentDate[1].ToString(CultureInfo.InvariantCulture) + segmentDate[2].ToString(CultureInfo.InvariantCulture) + segmentDate[3].ToString(CultureInfo.InvariantCulture);
var month = segmentDate[4].ToString(CultureInfo.InvariantCulture) + segmentDate[5].ToString(CultureInfo.InvariantCulture);
var day = segmentDate[6].ToString(CultureInfo.InvariantCulture) + segmentDate[7].ToString(CultureInfo.InvariantCulture);
//s[8] == "T";
var hours = segmentDate[9].ToString(CultureInfo.InvariantCulture) + segmentDate[10].ToString(CultureInfo.InvariantCulture);
var minutes = segmentDate[11].ToString(CultureInfo.InvariantCulture) + segmentDate[12].ToString(CultureInfo.InvariantCulture);
var seconds = segmentDate[13].ToString(CultureInfo.InvariantCulture) + segmentDate[14].ToString(CultureInfo.InvariantCulture);
string milliseconds = null;
if (segmentDate.Contains("."))
milliseconds = segmentDate.Split('.')[1].Split('-')[0];
if (milliseconds != null && milliseconds.Contains((" ")))
{
milliseconds = milliseconds.Split(' ')[0];
}
var offset = Convert.ToInt32(segmentDate.Split('-')[1].Split('/')[0]);
var a = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month),
Convert.ToInt32(day), Convert.ToInt32(hours), Convert.ToInt32(minutes),
Convert.ToInt32(seconds), Convert.ToInt32((milliseconds ?? "0"))).AddHours(offset);
But that is a bad idea - and I cannot believe that this format isnt specified somewhere (that I have been able to find).
Any help is appreciated.
Thank you!
Update
4 digit year
2 digit month
2 digit day
T - denotes start of the time portion
2 digit hour
2 digit minute
2 digit second
. - denotes start of MS
3 digit ms
TZ offset (-04)
/0 I believe is offset minutes
Update2
So I have been playing with TryParseExact and ParseExact - and cannot come up with a format string that will pull this into a DateTime/DateTimeOffset type.
I also consulted with the supplier of this value and they also have a manual process to parse it out, like I posted already.
I cannot accept that this is the only way to achieve the desired result, and as such, will continue to play with it.
But if anyone else has suggestions, they are welcome here.
Here's the closest I've gotten:
string s = "20141013T155544.673-04/0";
var dt = DateTime.ParseExact(s,"yyyyMMddTHHmmss.fffzz/0",CultureInfo.InvariantCulture);
If the /0 represents minutes (and can be 0 or 30 then you could do a little manipulation to convert that to a "standard" time zone indicator:
string s = "20141013T155544.673-04/30";
string s2 = s.Replace("/0",":00").Replace("/30",":30");
var dt = DateTime.ParseExact(s2,"yyyyMMddTHHmmss.fffzzz",CultureInfo.InvariantCulture);

change xml data in c#

I got acces to a XML file with the following data:
<VertrekTijd>2014-05-26T11:15:00+0200</VertrekTijd>
I use the following code to read this data:
case "VertrekTijd": lblv1.Text = (nodelist2.InnerText); break;
I recieve this in my label:
2014-05-26T11:15:00+0200
How do i get only the:
11:15
I looked around here but i didn't find any results.
One option is to use parsed time data from DateTime:
var date = DateTime.Parse( "2014-05-26T11:15:00+0200", System.Globalization.CultureInfo.InvariantCulture);
var res = date.Hour + ":" + date.Minute;
Another way is direct parsing with regular expression:
var res = Regex.Match("2014-05-26T11:15:00+0200", #"\d{1,2}:\d{1,2}").Value;
Yet another way is to play with string.Split and similar, but I wouldn't do that if you care about you mental health...
You can parse your time into a DateTime object and then present it:
DateTime dateTime;
if (DateTime.TryParse("2014-05-26T11:15:00+0200", out dateTime))
{
lblv1.Text = string.Format("{0}:{1}", dateTime.Hour, dateTime.Minute);
}

How to convert date to 'ccyymmddhhmmss' format?

How to convert date to 'ccyymmddhhmmss' format in c#?
You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));
From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.
#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

String was not recognized as a valid DateTime when converting to DateTime

I'm trying to convert a string to DateTime and then insert it to sql.
In my local computer all works fine, but on the server the application throws an exception:
String was not recognized as a valid DateTime
I use Textboxs to create a datetime object like this:
I'm using this line to build the date:
start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue;
end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue;
and then convert it
This is the code after the button click:
act_event add_event = new act_event();
string start, end;
DateTime strt_date = new DateTime();
DateTime end_date = new DateTime();
add_event.name = name_event.Text;
start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue;
end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue;
strt_date = Convert.ToDateTime(start); //This is the line that throws the error
add_event.start = strt_date;
end_date = Convert.ToDateTime(end);
add_event.end = end_date;
add_event.description = des_event.Text;
add_event.address = loc_event.Text;
db.add_event(add_event);
Then I get this:
The problem you are having most likely links to formatting issues. Since DateTime has a lot of different ways it can be formatted, the Convert.ToDateTime( ... ) is probably using a format that is different from your hour\minute format.
Try using DateTime.Parse \ DateTime.TryParse \ DateTime.ParseExact
See:
Convert.ToDateTime
DateTime.Parse
DateTime.ParseExact
.NET DateTime.Parse
Parse string to DateTime in C#
See Custom Date and Time Format Strings for formatting strings
It's probably a formatting\localization issue, different machines may be set to different locales and expect the dates to written differently.
I think you're getting yourself into unneeded trouble. Why create the string in the first place only to parse it later? Wouldn't it be easier to do something like -
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
with the data from the controls?

Categories

Resources