C# build date as string with leading 0s and no separators - c#

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.

Related

Converting a string into a 24hr datetime format

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.

C#, convert string to DateTimeOffset

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]));

Convert string from xml to DateTime

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.

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

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.

Remove leading zero form month C#

I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Totally doesn't work here.
This is my code:
string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");
Test is now 01 April
I just need it to be 4 in a string or int idc
Thanks!
Edit if I do:
billrunDate.ToString("(M)");
I get (4), but I dont need ()
EDIT 2:
Well this works
string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();
Very very ugly
It's interpreting M as a standard date and time format for "month day pattern".
To interpret a single character pattern as a custom date and time pattern, just prefix it with %:
string test = billrunDate.ToString("%M");
One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").
Relevant section:
"M"
The month, from 1 through 12.
"MM"
The month, from 01 through 12.
"MMM"
The abbreviated name of the month.
"MMMM"
The full name of the month.
You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:
string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();

Categories