i read a ini-file with a saved Date/Time string inside.
[Data]
Update = 07.02.2014 13:30:36
Rate_s = 5
I have both values as string in my C# program.
Now i want to save the "Update" in a value (Update_old) and the next time i read the file i want to check if Update_old+Rate_s >= Update_new
Means
The first time i read the file:
Update_old = 07.02.2014 13:30:36
Then 10 seconds later
Update_New = 07.02.2014 13:30:46
I need to know if the time changed.
My question is now how to convert the string with the date and time into something where i can add the 5secs and how to compare then the two values (old+rate against new)
It is possible that a new time is only 5seconds later but i can be also 1day 5hours later.
Thanks for the help
You need to parse the string values into a DateTime struct using DateTime.Parse. Then simply compare with <, >, ==, or !=
DateTime Update_New = DateTime.Parse("07.02.2014 13:30:36");
if (Update_New > Update_old)
{
}
If you want to manipulate the values use the AddX on the DateTime
Update_New = Update_New.AddSeconds(5);
Update_New = Update_New.AddHours(5);
Update_New = Update_New.AddDays(1);
If you parse both Update_old and Update_new into DateTimes, one of the possible results of subtraction of 2 date times is a TimeSpan, which conveniently has properties like TotalSeconds i.e.
if ((UpdateNewDateTime - UpdateOldDateTime).TotalSeconds > 5)
{ ...
However, if you are doing a lot of date manipulation, I would suggest you to also consider looking at NodaTime. This also takes into consideration issues with standard .Net DateTime like TimeZones, daylight savings, and inconsistencies in human calendars.
You can use DateTime.ParseExact to get a datetime and TimeSpan.FromSeconds to get a TimeSpan of 5 seconds.
string Update_old = "07.02.2014 13:30:36";
string Rate_s = "5";
DateTime oldDt = DateTime.ParseExact(Update_old, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string Update_New = "07.02.2014 13:30:46";
DateTime newDt = DateTime.ParseExact(Update_New, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
TimeSpan seconds = TimeSpan.FromSeconds(int.Parse(Rate_s));
if (oldDt + seconds > newDt)
{
// ...
}
Side-note: instead of using ParseExact you can also use DateTime.Parse with the correct culture. In this case it could be german culture("de-DE"):
var deCulture = CultureInfo.CreateSpecificCulture("de-DE");
DateTime oldDt = DateTime.Parse("07.02.2014 13:30:36", deCulture);
DateTime newDt = DateTime.Parse("07.02.2014 13:30:46", deCulture);
Since it's a file i would not use DateTime.Parse without a culture because the current-culture could change.
convert string to datetime type;
DateTime start = (DateTime)strDateTime.toDate("dd.MM.yyyy H:mm:ss");
as Tim Schmelter said use TimeSpan to add period of time ( as an ex. 10 sec )
TimeSpan seconds = TimeSpan.FromSeconds(10);
and compare using operators <=, >=, ==, >, <.
Related
How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}
I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);
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);
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.
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.