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);
Related
I need only date in the yyyy-MM-dd format, but I'm getting (20/03/2018 0:00:00) date in wrong format.
var d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
var finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null);
Output i am getting --20/03/2018 0:00:00
expected -- 2018-03-20
I will try to explain what the others meant when they wrote "DateTime has no format".
DateTime is a C# type that has properties for year, month, day, etc.
If you want to print a DateTime, you first have to convert it to a string. During this conversion, you can define the output format.
Also, if you parse a string into a DateTime, you can define the expected input format.
This is what the "Standard Date and Time Format Strings" / "Custom Date and Time Format Strings" are for.
An example:
string d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
DateTime finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null); // not a string!
int year = finadate.Year; // year == 2018 (a number!)
int month = finaldate.Month; // month == 3 (a number again!)
string isoFormat = finaldate.ToString("yyyy-MM-dd"); // isoFormat == "2018-03-20"
string usFormat = finaldate.ToString("MM/dd/yyyy"); // usFormat == "03/20/2018"
// and so on...
Note that if you just call ToString() without specifying any format, the result will depend on the culture of the current thread (probably "en-Us" judging from the output you have shown). See DateTime.ToString Method.
DateTime always returns DateTime object with the time part.
To get expected output, you have to return string eg. DateTime.Now.ToString("dd-MM-yyyy")
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;
}
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.
I'm having two strings, date which has the DateTime which is converted to string, and another variable days which store the number of days (eg: 5), now what i have to do is that, I just want to add the date and days and the result should be in DateTime format.
How can I do this??
PArse the Date and add the days(which should be double)
DateTime endDate = DateTime.Parse(date).AddDays(Convert.ToDouble(days));
you just need to parse your date string into datetime, and then add days:
var resultDate = DateTime.Parse("your date string").AddDays(days);
You just need to parse it to a datetime and add the days to the converted date,
DateTime YourCurrentDate= DateTime.Parse(string s);
DateTime endDate = YourCurrentDate.AddDays(addedDays);;
in single line,
DateTime endDate = DateTime.Parse("string").AddDays(days);
How do I check for time for between. suppose I have Time in string format like "02:00 PM" and I want to check it between two other times. How can I check for this, as the time is in string format ?
The value to be compare with the times is store in DataTable, and I am using the Select function of the datatable.
Try DateTime.Parse(dateString1) > DateTime.Parse(dateString2).
If your string format is not compatible with the string format of DateTime, you'll need to parse your date manually.
Edit:
You can use ParseExact to specify your own format:
string Format = "T";
CultureInfo provider = new CultureInfo("en-US");
if (DateTime.ParseExact(dateString1, format, provider) >
DateTime.ParseExact(dateString2, format, provider))
{
...
You can always convert to string to a timespan (or datetime) something like this:
TimeSpan ts = Convert.ToDateTime("02:00 PM").TimeOfDay;
TimeSpan checkValue1 = Convert.ToDateTime("01:00 PM").TimeOfDay;
TimeSpan checkValue2 = Convert.ToDateTime("03:00 PM").TimeOfDay;
bool passed = (ts >= checkValue1 && ts <= checkValue2);
Convert it to a DateTime with the current date as date, or a TimeSpan representing the time from midnight:
DateTime time = DateTime.Parse(timeString);
Or:
TimeSpan time = DateTime.Parse(timeString).TimeOfDay;
Having the value as a TimeSpan might be easier when you compare it, otherwise you have to make sure that the DateTime values that you compare it to also have the current date as date. On the other hand, the DateTime value can be used to compare times across midnight, e.g. between 23.00 today and 01.00 tomorrow.