I have a XML file from which I read time stamps. When reading these time stamps using .InnerText I will get this for each node:
2016 6 9 15 8 28
My goal is to convert that string into this format:
2016-06-09T15:08:28.000000+00:00
Is there any solution for doing this?
XML example:
If the string will always be in the same format you can use DateTime.ParseExact to get a DateTime object.
var result = DateTime.ParseExact(innerText, "yyyy M d H m ss", CultureInfo.InvariantCulture);
The best method is to get every component of the date from the XML. If you want to start using the InnerText property, try to use this:
var input = "2016 6 9 15 8 28 ";
var parts = input.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries)
.Select(n => Int32.Parse(n)).ToArray();
var dt = new DateTime(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);
I prefer the method suggested by Alex above! :-)
First, parse year, month, day, hour, minute and second from your XML to integers, then use one of DateTime's constructors:
DateTime date = new DateTime(int year, int month, int day, int hour, int minute, int seconds);
Then format your date using one of the format strings.
Related
I have string data that comes in the following sequence:
"4:32", "1:08"
I want to convert this to 24hr time
where "4:32" becomes 16:32
Parse that to a TimeSpan, then add 12 hours:
var offset = TimeSpan.FromHours(12);
var time = TimeSpan.Parse("4:32").Add(offset);
Parse the input string to a TimeSpan, add 12 hours, then format the TimeSpan with the desired string format:
string input = "4:32";
string output = TimeSpan.Parse(input).Add(TimeSpan.FromHours(12)).ToString("hh\\:mm");
// output: "16:32"
As per your comment, once you know if the hour is AM/PM, you could parse the value with it's suffix and then use the HH custom format specifier:
DateTime d = DateTime.Parse("4:32 PM");
Console.WriteLine(d.ToString("HH:mm"));
to convert it to 24h format.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#HH_Specifier
In the simple case your question suggests, where you know beforehand that the string is 12-hour in the format h:mm and it refers to PM, never AM, then you can split the string, parse the hour, add 12, and reassemble it.
var inputString = "4:32";
var splits = inputString.Split(':');
var hourString = splits[0];
var minuteString = splits[1];
var hour = int.Parse(hourString);
hour = hour + 12;
var outputString = $"{hour}:{minuteString}";
If you're doing anything more complicated with dates or times, you probably want to use DateTime or similar classes.
I have a date. I would like to read out all the date parts into separate strings with leading 0s where applicable and then concatenate them to create a date string that is just numbers without any separators.
For example:
DateTime dt = DateTime.Now;
string year = dt.Year.ToString();
string month = dt.Month.ToString();
string day = dt.Day.ToString();
string hour = dt.Hour.ToString();
string minutes = dt.Minute.ToString();
string seconds = dt.Second.ToString();
string finalDt = string.Concat(year, month, day, hour, minutes, seconds);
I would like month to be 01 if it is January, day to be 03 if it is the third day, and likewise with hour, year, seconds. Is there a way to accomplish that without having to check the count for each datepart and pad it with a leading 0?
If there is a better way to accomplish what I'm trying to do overall, then I would like suggestions.
You can use DateTime.ToString(string format) for this purpse:
dt.ToString("yyyyMMddHHmmss")
Or if you still want to do each part separately:
string year = dt.Year.ToString("0000");
string month = dt.Month.ToString("00");
string day = dt.Day.ToString("00");
string hour = dt.Hour.ToString("00");
string minutes = dt.Minute.ToString("00");
string seconds = dt.Second.ToString("00");
What about using custom format-string in the DateTime.ToString method:
DateTime.Now.ToString("yyyyMMddhhmmss");
The DateTime type supports many ways of formatting, so you can build up the resulting format from individual "components". Refer to the Docs to see all the options available.
I am trying to convert a string into DateTimeOffset. here is an example of my string 2017/010/23:51:50 2017 represents year 010 represent day of the year and 23:51:50 is time.
I am trying in below way but it returns me 0001-01-01 00:00:00.0000000 +00:00 always no mater the input is.
My code
DateTimeOffset DateTime;
string year = ("2017/010/23:51:50");
DateTimeOffset.TryParse(year, out DateTime);
Any suggestion please?
Update
For simplicity I did not linger my question. My date time I am getting year (2017 it could be 2002, 2001 ) from name of a .txt file and day and time (010/23:51:50 some has offset and some content don't) from the content of that .txt file. So my input is not always same. hope this clarifies
First split the string by / and then use the dayOfTheYear value and the year to obtain the year/month/date. Next split the time parameter and use it to obtain TimeSpan and add it to the previously obtained date. Next, simply parse your newly obtained date to DateTimeOffset. This code should work:
string year = ("2017/010/23:51:50");
var date = year.Split('/');
var timeSpanVal = date[2].ToString().Split(':').Select(x=>Convert.ToInt32(x)).ToList();
TimeSpan ts = new TimeSpan(timeSpanVal[0], timeSpanVal[1], timeSpanVal[2]);
DateTime newDate = new DateTime(Convert.ToInt32(date[0]), 1, 1).AddDays(Convert.ToInt32(date[1]) - 1)+ts;
DateTimeOffset.TryParse(newDate.ToString(), out DateTime);
Looking through the date and time formats, I don't think you can parse the format Year/JulianDay/Time. What you can do is split the string into parts and then add the days to the year
string[] parts = year.Split('/');
DateTime dt = new DateTime(int.Parse(parts[0]), 1, 1);
dt = dt.AddDays(int.Parse(parts[1]) - 1).Add(TimeSpan.Parse(parts[2]));
I'm trying to Split this string: 2015-08-14 20:30:00
but the compiler shows this message:
Can't convert from String to Char
This is my code:
string date = reader["date"].ToString().Split("-").ToString();
The variable reader["date"] is an object, so I must convert it into a String. I want to Split the content into three other variable like this:
year: 2015
month: 08
day: 14
What am I doing wrong?
There is no String.Split overload that takes string as a parameter. That's why it looks closest overload which is char[] but there is no implicit conversation between them.
var array = "2015-08-14 20:30:00".Split(new char[]{'-', ' '});
will return
and you can get them with array[0], array[1] and array[2].
Also you can use to parse your string to DateTime instead (which your string is valid one) of splitting it like;
string s = "2015-08-14 20:30:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// dt.Year;
// dt.Month;
// dy.Day;
}
But since these properties are int, you will not get leading zeros for your single digit month and days.
In such a case, you can choose to use dd and MM custom date and time format specifiers.
Sometime a different approach should be considered. If your reader field datatype is date or datetime then using the correct datatype is the correct way to handle this info. A DateTime has already all you need.
DateTime dt = Convert.ToDateTime(reader["date"]);
int year = dt.Year;
int month = dt.Month;
int day = dt.Day;
As String.Split reaturns an array of strings you need date to be the same. So simply write
string[] date = Convert.ToString(reader["date"]).Split("-");
Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.