How to convert the "time" from DateTime into int? - c#

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;
}

Related

Convert time string to DateTime in c#

How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);

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

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

Join date and time strings into a DateTime

Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;

Converting String (Textbox.text) to DateTime with current time

I am trying to convert this e.g. 12/31/2012 format into DateTime, however when I run this code the conversion works but the time is not current. I am looking to convert to DateTime but with the current time:
Example: When I run the below code and enter date: 12/31/2012
I get: 12/31/2012 12:00:00 AM
I am not sure how to get the current time instead of 12:00:00 AM
Console.Write("Enter Current Date: ");
string strMyDate = Console.ReadLine();
DateTime dt = DateTime.Parse(strMyDate);
Console.WriteLine(dt);
Console.ReadKey();
You can extract only the time from DateTime.Now by using the TimeOfDay property and add it to your manually entered date, e.g.
var time = dt.Add(DateTime.Now.TimeOfDay);
As an additional note, I would use DateTime.TryParse instead, as the value entered by the user may not be a parseable date, e.g.
DateTime dt;
var isDate = DateTime.TryParse(strMyDate, out dt);
if(isDate)
{
var time = dt.Add(DateTime.Now.TimeOfDay);
}
DateTime.Now will give you current time. Than combine date portion from first value with time portion from Now to get the result.
Add this to your string:
string strMyDate = Console.ReadLine();
strMyDate = string.Format("{0} {1}",
strMyDate,
DateTime.Now.ToShortTimeString());
Haven't actually compiled this but something like this should work:
DateTime dt = DateTime.Parse("12/31/2012 " + DatTime.Now.TimeOfDay.ToString());
You can build up the time from the hours, minutes and seconds portion of DateTime.Now;
string strMyDate = "12/31/2012";
DateTime dt = DateTime.Parse(strMyDate);
DateTime current = DateTime.Now;
dt = dt.AddHours(current.Hour).AddMinutes(current.Minute).AddSeconds(current.Second);
Console.WriteLine(dt);

Categories