Converting string to TimeSpan type - c#

I have method which the datatype is TimeSpan. How can I convert it to a string?
This is my Model code:
private TimeSpan starttime;
public TimeSpan ShiftStartTime
{
get { return starttime; }
set
{
starttime = value;
OnPropertyChanged("ShiftStartTime");
}
}
This is my ViewModel code:
ShiftStartTime = ??reader[3].ToString()
The reader here represents my MySqlDataReader.

If your time format is "HH:mm:ss" then you can simply do:
ShiftStartTime = TimeSpan.Parse(reader[3].ToString());
If for example the value in your db is "20:30:21" then the TimeSpan object will store:
Hours: 20
Minutes: 30
Seconds: 21

You can use DateTime.ParseExact() method as below. You can pass format accordingly.
TimeSpan ts = DateTime.ParseExact(
reader[3].ToString(),
"HHmmss",
System.Globalization.CultureInfo.InvariantCulture
).TimeOfDay;

Related

How to convert the "time" from DateTime into int?

I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}

How to get a DateTime from total amount of seconds?

Let's say I have
int seconds = 43200;
(amount of seconds from the beginning of the current day, 00:00:00) and I want to get related DateTime representation ("12:00:00"). Is there any c# utility function?
You need the TimeSpan, then you can get the DateTime in this way:
TimeSpan timeOfDay = TimeSpan.FromSeconds( seconds );
DateTime dt = DateTime.Today.Add( timeOfDay );
It is not a DateTime representation, it looks like a TimeSpan representation to me instead.
For this, you can use TimeSpan.FromSeconds method like;
int seconds = 43200;
var ts = TimeSpan.FromSeconds(seconds);
If you really need to add this to generate current day midday, you can use DateTime.Today property and add this to that.
DateTime dt = DateTime.Today.Add(ts);
You can calculate it directly:
int seconds = 43200;
DateTime dateTime = DateTime.Today.AddSeconds(seconds);

How to split string value using c# asp.net

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.
August 11, 45 minutes ago
The given datetime(i.e-2015-08-11 10:59:41.830) will compare with the current datetime and display like the above format.Please help me to do this.
You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date (DateTime.Now) and subtract from it the parsed date.
This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).
For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"
static void Main(string[] args)
{
//Given that previous and and now is the same day
DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
double value = now.Subtract(previous).TotalMinutes;
Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
Console.ReadLine();
}
npinti already explained it, here the code part;
string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
var ts = dt - DateTime.Now;
Console.WriteLine("{0}, {1} minutes ago",
dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
ts.Minutes);
}
I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.
Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59. If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes).
You need this
var yourString = "2015-08-11 10:59:41.830";
var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
//The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
var difference = DateTime.Now - oldDate;
//here old date is parsed from string or your date in `DateTime` format
var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

How do i assign back the DateTime.Now from a string?

The code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime.Now = time;
}
time now for example show the saved datetime.now could be minute ago or an hour ao.
the datetime.now is saved after my program is finished to make an operation.
dt = the current datetime now i use this method in the constructor.
What i want to do is to calculate the time that have been passed between the last saved datetime.now(time) and the current datetime.now(dt).
If the time that have been passed is 20 minutes or more enable true a button.
You cannot set DateTime.Now You need to create an instance of the DateTime object.
Then to get the difference you can say
TimeSpan diff = DateTime.Now - MyDateTime;
This has a property called TotalMinutes that you can use for your check.
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
You can try this code
DateTime date;
if (DateTime.TryParse(time, out date))
{
TimeSpan diff = date - dt;
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
}
Every time you run this method you need to persist the value somewhere. I'm going to call that variable _lastTime. That's going to be a DateTime. Further, you'll need a variable for the actual elapsed time between those two, we'll call that _elapsedTime. That's going to be a TimeSpan. With that in mind, consider this code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
var dt = DateTime.Parse(time);
_elapsedTime = dt.Subtract(_elapsedTime);
_lastTime = dt;
}
You get an instance of a DateTime from a string using Parse
DateTime dt = DateTime.Parse(time)
and then you get get the time Now using
DateTime.UtcNow; or DateTime.Now;
and subtract one from the other and format as appropriate for you output
You can do this using TimeSpan.
you need to get the Difference in Minutes
DateTime dt1;//get your first date
TimeSpan duration = DateTime.Now - dt1;
if(duration.Minutes>20)
Button1.Enabled=true;
I think your looking for this:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime lastTime = DateTime.Parse(time);
if (DateTime.Now - lastTime > new TimeSpan(0, 20, 0))
{
//It's passed more than 20mins from last save.
}
}
You can check the time elapsed by using the TimeSpan class.
private void beginOperstionChecker(DateTime dt)
{
if(TimeSpan.FromMinutes(20) == DateTime.Now - dt)
{
//do your stuff here
}
}

How do I convert a 12 hour time string into a C# TimeSpan?

When a user fills out a form, they use a dropdown to denote what time they would like to schedule the test for. This drop down contains of all times of the day in 15 minute increments in the 12 hour AM/PM form. So for example, if the user selects 4:15 pm, the server sends the string "4:15 PM" to the webserver with the form submittion.
I need to some how convert this string into a Timespan, so I can store it in my database's time field (with linq to sql).
Anyone know of a good way to convert an AM/PM time string into a timespan?
You probably want to use a DateTime instead of TimeSpan. You can use DateTime.ParseExact to parse the string into a DateTime object.
string s = "4:15 PM";
DateTime t = DateTime.ParseExact(s, "h:mm tt", CultureInfo.InvariantCulture);
//if you really need a TimeSpan this will get the time elapsed since midnight:
TimeSpan ts = t.TimeOfDay;
Easiest way is like this:
var time = "4:15 PM".ToTimeSpan();
.
This takes Phil's code and puts it in a helper method. It's trivial but it makes it a one line call:
public static class TimeSpanHelper
{
public static TimeSpan ToTimeSpan(this string timeString)
{
var dt = DateTime.ParseExact(timeString, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
return dt.TimeOfDay;
}
}
Try this:
DateTime time;
if(DateTime.TryParse("4:15PM", out time)) {
// time.TimeOfDay will get the time
} else {
// invalid time
}
I like Lee's answer the best, but acermate would be correct if you want to use tryparse. To combine that and get timespan do:
public TimeSpan GetTimeFromString(string timeString)
{
DateTime dateWithTime = DateTime.MinValue;
DateTime.TryParse(timeString, out dateWithTime);
return dateWithTime.TimeOfDay;
}
Try:
string fromServer = <GETFROMSERVER>();
var time = DateTime.Parse(fromServer);
That gets you the time, if you create the end time as well you can get Timespans by doing arithmetic w/ DateTime objects.

Categories