C#, convert string to DateTimeOffset - c#

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

Related

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.

Conversion to Time 12 hour Format From String containing Time in 24 hour format

I have a varchar(5) column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded
with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime
column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
The format for printing uses "hh:mm:ss tt" because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;
The full date and time is constructed based on DateTime.Today which returns the today date with a zeroed time and then we just add the time we read from input.
To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
DateTime Structure;
Custom Date and Time Format Strings;
Standard DateTime Format Strings.
create function dbo.COMBINE_DATE_TIME(
#DatePart DateTime, -- DateTime
#TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,#DatePart),
CONVERT(DateTime,ISNULL(#TimePart,''),14))
end
go
string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");
string fromTime = Convert.ToStr(reader["TimeFrom"]);
string toTime = Convert.ToStr(reader["TimeTo"]);
item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");
here the property of your model(item.Time here) should be the string.

c# show only Time portion of DateTime

I have a date that shows up as 10/18/2011 3:12:33 PM
How do I get only the time portion of this datetime?
I am using C#.
I tried:
string timeval = PgTime.ToShortTimeString();
but that did not work as Intellisense only showed ToString();
Assuming that
DateTime PgTime;
You can:
String timeOnly = PgTime.ToString("t");
Other format options can be viewed on MSDN.
Also, if you'd like to combine it in a larger string, you can do either:
// Instruct String.Format to parse it as time format using `{0:t}`
String.Format("The time is: {0:t}", PgTime);
// pass it an already-formatted string
String.Format("The time is: {0}", PgTime.ToString("t"));
If PgTime is a TimeSpan, you have a few other options:
TimeSpan PgTime;
String formattedTime = PgTime.ToString("c"); // 00:00:00 [TimeSpan.ToString()]
String formattedTime = PgTime.ToString("g"); // 0:00:00
String formattedTime = PgTime.ToString("G"); // 0:00:00:00.0000000
If you want a formatted string, just use .ToString(format), specifying only time portions. If you want the actual time, use .TimeOfDay, which will be a TimeSpan from midnight.
DateTime PgTime = new DateTime();
var hr = PgTime.Hour;
var min = PgTime.Minute;
var sec = PgTime.Second;
//or
DateTime.Now.ToString("HH:mm:ss tt") gives it to you as a string.
Don't now nothing about a class named PgTime. Do now about DateTime, though.
Try
DateTime instance = DateTime.Now ; // current date/time
string time = instance.ToString("t") ; // short time formatted according to the rules for the current culture/locale
Might want to read up on Standard Date and Time Format Strings and Custom Date and Time Format Strings
In C# 10 you can use TimeOnly.
TimeOnly date = TimeOnly.FromDateTime(PgTime);

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

Combine date and time when date is a DateTime and time is a string

I am working with an old mysql database in which a date is stored (without a time) as a datetime and a time is stored as a string (without a date).
In C# I then have a DateTime with a value like 2010-06-25 12:00:00 AM and a String with a value like 15:02.
What is the most concise way to combine these without a lot of overhead?
I have tried a few methods including:
DateTime NewDateTime = DateTime.Parse(OldDateTime.ToString("yyyy-MM-dd ") + TimeString);
I dislike converting the existing DateTime to a string and appending the time.
I can convert the time string to a date, but then I get today's date and adding it as a number of ticks to the old datetime is incorrect.
Note: Don't worry about validation, it is done elsewhere. The time is represented using 24-hour format without seconds.
You can use TimeSpan.Parse to parse the time, and then add the result to the date:
DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));
var dt = new DateTime(2010, 06, 26); // time is zero by default
var tm = TimeSpan.Parse("01:16:50");
var fullDt = dt + tm; // 2010-06-26 01:16:50
I used something similar to what simendsjo says, except I continued to have it as a DateTime
DateTime date = Convert.ToDateTime(txtTrainDate.Text);
DateTime time = Convert.ToDateTime(ddTrainTime.SelectedValue);
DateTime dtCOMPLTDTTM = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
I think you're worrying about the string conversion too much. By combining the 2 string elements together you are saving further date string parsing anyway which will most likely be more expensive.
Is this going to be repeated a lot of times or a simple step in a larger process?
I am fairly sure you could combine and convert these values into a timestamp using SQL.

Categories