change xml data in c# - 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);
}

Related

Parsing a string like "03/2020" to a DateTime variable

I have to parse a string, which always look like 03/2020 (so the format is MM/yyyy), to a DateTime variable.
How do I achieve it the most proper way? (Without splitting the string into substrings)
I already found the DateTime.ParseExact function, but I'm confused by the third parameter (culture-specific format information).
Is the DateTime.ParseExact the way to go or is there a better function/way to achieve the goal?
var inputString = "03/2020";
var inputStringFormat = #"MM/yyyy";
// var inputStringAsDateTime = ???
Edit 1
As additional info I have to say, that the string (inputString) is read from a barcode. So the separator in it is always the /.
Tim Schmelter explained in his answer, how to mask such separators.
It looks like I have to change my inputStringFormat variable to:
var inputStringFormat = #"MM'/'yyyy";
If the first day of the month is good for you, you can use DateTime.ParseExact:
var d = DateTime.ParseExact(inputString, inputStringFormat, CultureInfo.InvariantCulture);
Usually, i use ToDateTime method of Convert class. I have tested it, it's working.
string inputString = "03/2020";
DateTime datetime = Convert.ToDateTime(inputString));
It will give output like 3/1/2020 12:00:00 AM means it will gives you output according to your system's date format.
With such simple date format you can use
var inputArr = inputString.split(#"/");
var inputStringAsDateTime = new DateTime(inputArr[0], inputArr[1], 1);
however for culture you can use constant
CultureInfo.InvariantCulture

String was not recognized as a valid DateTime when using DateTime.ParseExact

I have below piece of code to log the message. Since I wanted to have the log for each date I tried to retrieve current date and then tried to create log file with that particular date with format path/dd_mm_yyyy_LogFile.txt. Before that I had to retrieve current date without time.
StreamWrite sw=null;
var d = Convert.ToString(DateTime.Today.ToShortDateString());
var date = DateTime.ParseExact(d, "dd_MM_yyyy", CultureInfo.InvariantCulture);
//Error in the above line
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + d + "_LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);
But am getting String was not recognized as a valid DateTime. I followed many other posts like changing the "dd_MM_yyyy" to "dd-MM-yyy" or to "d-m-yyyy" but unfortunately am still hitting the same error. What else am missing here? Below screenshot for reference. If you see the screenshot, I've proper d value fetched. But still the above exception.
As I can see from the picture, you actually want "M/d/yyyy" format:
String d = #"2/26/2016"; // d's value has been taken from the screenshot
DateTime date = DateTime.ParseExact(d, "M/d/yyyy", CultureInfo.InvariantCulture);
Create d like this instead:
var d = DateTime.Today.ToString("dd_MM_yyyy");
ToShortDateString() does not have the format you want.
Your format string in Parse method should exactly match the one produced by ToShortDateString. e.g. this works with me:
var d = Convert.ToString(DateTime.Today.ToShortDateString());
Console.WriteLine(d);
var date = DateTime.ParseExact(d, #"MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);
output:
02/26/2016
02/26/2016 00:00:00
Look at the screen shot you posted. The runtime value of the string is:
"2/26/2016"
So the format string should be:
"M/dd/yyyy"
or:
"MM/dd/yyyy"
By using those other format strings, you're explicitly telling the system to use that exact format. And the string you have doesn't match that format. Hence the error.

c# convert PDF metadata CreationTime to DateTime

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.

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

Formatting any string to string "yyyy/MM/dd" [duplicate]

This question already has answers here:
Date formatting yyyymmdd to yyyy-mm-dd
(9 answers)
Closed 5 years ago.
I have many strings like "20120117" and "20120321". I need to convert it in a new string with this format: "2012/01/17" and "2012/03/21". So, there is a way to do this?
I try:
string dateString = string.format("{0:d", "20120321");
and
string dateString = string.format("{0:yyyy/MM/dd", "20120321");
and
string dateString = int.Parse("20120321").ToString("yyyy/MM/dd");
I all cases i don't reach my goal. =/
So, i can i do this?
OBS: There is a way to do that without parse to datetime?
You have to parse those values in DateTime objects first.
Example :
DateTime dt = DateTime.ParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var result = dt.ToString("yyyy/MM/dd");
Edit after your comments on other answers:
if you don't like parsing because it may throw excepations, you can always use TryParse, like this:
DateTime dt;
bool success = DateTime.TryParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
}
Edit 2: Using TryParseExact with multiple formats:
DateTime dt;
string[] formats = { "yyyyMMdd", "yyyy" };
bool success = DateTime.TryParseExact("20120321", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
Console.WriteLine(result);
}
It will produce 2012/03/21 when using "20120321" as input value, and 2012/01/01 when using 2012 as input value.
DateTime.ParseExact("20120321", "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy/MM/dd")
You could parse the string but this method gives you validation without any extra code. Imagine receiving "20120230", "20110229", or any other invalid date.
From your comments:
There is a way to do that without parse to datetime?
Yes, absolutely. If you really want to propagate bad data through your system rather than highlighting that it's incorrect, you could definitely use:
// Make sure we'll always be able to get a result whatever the input.
string paddedInput = input + "????????";
string mightBeBadWhoKnows = string.Format("{0}/{1}/{2}",
paddedInput.Substring(0, 4), // The year, if we're lucky
paddedInput.Substring(4, 2), // The month, if we're lucky
paddedInput.Substring(6, 2)); // The day, if we're lucky
But why wouldn't you want to spot the bad data?
You absolutely should parse the data. If you want to be able to continue after receiving bad data having taken appropriate action, use DateTime.TryParseExact. If you're happy for an exception to be thrown, use DateTime.ParseExact. I'd suggest using the invariant culture for both parsing and formatting, unless you really want a culture-sensitive output.
Use DateTime.ParseExact to convert to a DateTime, then use ToString on that instance to format as you desire.
DateTime.ParseExact(dateString, "yyyyMMdd").ToString("yyyy/MM/dd");
EDIT: using Insert:
EDIT2: Fixed bugs :-)
var newString = dateString.Insert(4, "/").Insert(7, "/");
Just use string operations to insert the slashes:
string input = "20120321";
string dateString =
input.Substring(0, 4) + "/" +
input.Substring(4, 2) + "/" +
input.Substring(6);
or
string dateString = input.Insert(6, "/").Insert(4, "/");
If it's a date, try this:
DateTime.ParseExact("20120321","yyyyMMdd", null).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
try this;
string dateString = DateTime.ParseExact("20120321", "yyyyMMdd",
null).ToShortDateString();
If your data is always in the same format and if you don't need to validate it, you can use the following snippet to avoid parsing it with DateTime
var strWithInsert = input.Insert(4,"/").Insert(7,"/");

Categories

Resources