Convert 20141013T155544.673-04/0 to DateTime C# - 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);

Related

0 Character Problem in the beggining DateTime

I got every part of date in the code that you can see below. But the problem is if we consider today's date I need day and month as 02 not as 2.
I need that 0 char in the beggining. How can I manage it?
DateTime dategift = DateTime.Now;
var year = dategift.Year.ToString();
var month = dategift.Month.ToString();
var day = dategift.Day.ToString();
var hour = dategift.Hour.ToString();
var min = dategift.Minute.ToString();
var sec = dategift.Second.ToString();
use the Zero placeholder
string day = dategift.Day.ToString("00");
or the "dd" custom format specifier
string day = dategift.ToString("dd");
If you're wanting to format the date, you can do so without pulling out all the various values as strings.
Something like:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

How to subtract time (HHH:MM)

I want to Subtract two time strings that I read from an excel sheet, for example 150:24 and 124:30.
The time format is HHH:MM in the excel sheet. How can I subtract these two strings in C#?
I can not illustrate the data format! also I can not write true code for this issue.
You can calculate the times difference based on minutes. Then convert to any format you want...
var s1 = "150:24".Split(':');
var s2 = "124:30".Split(':');
var diffMinutes= int.Parse(s1[0]) * 60 + int.Parse(s1[1]) - int.Parse(s2[0]) * 60 - int.Parse(s2[1]);
Console.WriteLine("difference in minutes: " +diffMinutes);
//difference in minutes: 1554
Console.WriteLine("difference in HHH:MM: "+ diffMinutes/60 + ":"+diffMinutes%60);
//difference in HHH:MM: 25:54
TimeSpan t= TimeSpan.FromMinutes(result);
Console.WriteLine(t);
//1.01:54:00
TimeSpan.Parse unfortunately does not work is the hour part is > 23. But of course it is possible to split on the ':', convert the hour and minute parts to integers separately and construct a TimeSpan from it:
public static TimeSpan ParseHoursAndMinutes(string s)
{
// NOTE: no error checking!
var parts = s.Split(':');
var hours = int.Parse(parts[0]);
var minutes = int.Parse(parts[1]);
return new TimeSpan(hours, minutes, 0);
}
var diff = ParseHoursAndMinutes("150:24") - ParseHoursAndMinutes("124:30");
Console.WriteLine(diff); // => 1.01:54:00

store zeros after decimal point in variable in c#

my application in c# is on payroll management system...and i would like to have the work hours of each employee in variable ...for this i m using double ...suppose an employee works for 8 hours and 20 min ..then the entry will be like 8.20 in text box...so i am separating the part before decimal in one variable using`
var values = totaldays.ToString(CultureInfo.InvariantCulture).Split('.');
int firstno = int.Parse(values[0]);
int secondno = int.Parse(values[1]);`
so i m getting first variable accurately but if part after decimal contains zeros it not storing in "secondno" variable . the zeros get eliminated automatically and the result for 8.20 and 8.2 is same i.e., 8.2 .
but since the time is different one is 8 hours 20min and other is 8 hours 2min ..i want some solution to to do this ..please help me since my whole application is dependent on this.
If the user is entering hours and minutes, why not use a TimeSpan?
var input = "8.20";
var time = TimeSpan.ParseExact(input, #"h\.mm", null);
var hours = time.Hours; // 8
var minutes = time.Minutes; // 20
Further Reading
Custom TimeSpan Format Strings
If you really must store it as a decimal first, you can still manage using this:
var input = 8.20m;
var parts = input.ToString("0.00", CultureInfo.InvariantCulture).Split('.');
var hours = int.Parse(parts[0]); // 8
var minutes = int.Parse(parts[1]); // 20
But as Ellesedil points out, you'll have to decide how to handle values like 8.70.
Try something like this. This is off the top of my head:
int hours = Math.Floor(totaldays);
int minutes = (totaldays - Math.Floor(totaldays)) * 100;
You can just format double with f2 format specifier
double d = 8.20;
string str = d.ToString("f2", System.Globalization.CultureInfo.InvariantCulture)
int hour = int.Parse(str.Split('.')[0]);
int min = int.Parse(str.Split('.')[1]);
thats it you are done

how to achieve timespan to string conversion?

I tried searching here, but it couldn't help me much ..
I want to convert time_span to string, I don't want to return the timespan in days .. but only HH:mm:ss. How to achieve that?
My sample code is here:
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString("HH:mm:ss");
Try using
DateTime d = new DateTime(time_span.Ticks);
string time = d.ToString("HH:mm:ss");
This should work:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString(), time_span.Minutes.ToString(),
time_span.Seconds.ToString());
As per comment if you want the double digits you could do:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString("00"), time_span.Minutes.ToString("00"),
time_span.Seconds.ToString("00"));
Edited:as per jimmy's comment,
string temp = string.Format("{0:00}:{1:00}:{2:00}",time_span.Hours, time_span.Minutes, time_span.Seconds);
Try this:
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString();
temp = string.Format("{0}:{1}:{2}", time_span.TotalHours, time_span.TotalMinutes, time_span.TotalSeconds);
Edit
After I read your comment on your question, that is you need to display zero hours for new days, my answer will give you total hours, minutes and seconds, not what you want.
(+1) Kelseys ;)
The code I have implemented is:
string temp = DateTime.Today.Add(time_span).ToString("HH:mm:ss");
Originally posted by Marc Gravell,
There is a much simpler way of doing this now (albeit only using framework 4), you just need to use the string literally, and you can do it directly on the TimeSpan instance.
time_span.ToString(#"hh\:mm\:ss")
That will output
00:26:39
Helpful now for people stumbling across this (like myself).
Cheers :)
Simply convert the value of ticks into a DateTime and then use its ToString()
var date1 = DateTime.Now;
var date2 = DateTime.Now.AddSeconds( -1000 );
var diff = date1 - date2;
var temp = new DateTime( diff.Ticks ).ToString( "HH:mm:ss" )
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
TimeSpan finalTime = (time_span_var + time_span);
Console.WriteLine(finalTime);
Console.WriteLine(finalTime - TimeSpan.FromHours(finalTime.Days * 24));
If the number of days is irrelevant then you have the solution, however I came across this answer searching for a conversion that gave hours in total, so 36 hours would need to be displayed as 36:00:00. Using some of the hints above this is what I came up with:
SomeLabel.Text = Math.Floor(ts.TotalHours).ToString() + ":" + ts.Minutes.ToString("D2") + ":" + ts.Seconds.ToString("D2");
Total Hours is always rounded down, minutes and seconds are padded to be 2 digits (00 - 09)

Question about TimeZones and Jquery CountDown plugin

I am looking to use this plugin: http://keith-wood.name/countdown.html
but I need to use the TimeZone feature of it. So I was looking at the sample code
$('#sydneyCountdown').countdown({until: liftoffTime, timezone: +10});
so +10 is the TimeOffSet number. Now I need to make it so I can do a jquery get request and grab the TimeOffSet from the server(which gets the users time from the db and does TimeOffSet).
However it seems that C# TimeOffSet returns something like this "+02:00"(not this is just a random zone not the same as the one in the jquery example).
So it seems like all the C# TimeOffSet follow that format +/-xx:xx
So I don't understand why the jquery plugin is only 2 digts while the other one is 4 digits.
Can I know off safley the last 2 digits in the C# tomatch the plugin format?
Edit - would this work?
// working on how to get offsetTime will be posted soon.
string time = "-08:30";
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
So just convert the hours to mins and then add the mins to it?
Edit - With offSetTime
var info = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
TimeSpan span = info.BaseUtcOffset;
string time = Convert.ToString(span);
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
Problem though OffSet only gives me the number not the +/- sign. So I don't know how to get it.
Edit -
Never mind I it makes sense that they don't add the plus sign since I was just testing one that would have a "-" sign and it is shown.
The plugin says:
Cater for time zones with the timezone
setting, which is set to the target
time's offset from GMT, in either
hours or minutes.
So, I think based on the magnitude of the timezone value, it treats it either as hours or minutes. You should convert the <sign><hh>:<mm> format to into number of minutes, to account for timezones that are not hour-aligned. Something like:
var tz = "-08:30";
var tz_tokens = /([+\-])0?(\d+):(\d+)/.exec(tz);
var tz_minutes = (tz_tokens[1] + 1) * (tz_tokens[2] * 60 + tz_tokens[3]);
// ..., timezone: tz_minutes, ...

Categories

Resources