I can't find a way to find all the dates(strings) less then at least one year from now.
i keep in database Date Field strings like "DateTime.toShortDateString()" and i need to compare now.
it looks like month/day/year = 9/6/2011
its need to be lower at least one year from DateTime.now.
i did this and it doesnt return all dates needed just few.
DateTime Date = DateTime.Now;
int Year = Date.Year;
Year -= 1;
int Month = Date.Month;
string MonthYear = Month.ToString() + "%" + Year.ToString();
string Query = "SELECT * FROM Orders WHERE DateOrder < #STU ";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.Parameters.AddWithValue("#STU", MonthYear);
This is my problem
Modify your database schema and store dates as char(10) in ISO 8601 format (yyyy-mm-dd) or the ISO 8601 compact form (yyyymmdd).
http://www.cl.cam.ac.uk/~mgk25/iso-time.html
http://en.wikipedia.org/wiki/ISO_8601
That gives you proper collation and proper comparison. Further...DateTime.Parse() and TryParse() will both accept that format regardless of culture (well..one exception: Saudi Arabia, ar-SA. Go figure). DateTime.ToString("Y") orstring.Format( "{0:Y}" , someDateTimeInstance )` will give you the ISO 8601 format.
Should be a simple update to your database.
Even better, if you're using SQL Server 2008: store dates using the new datatype Date.
Maybe deserialize these DateTime strings and then compare as DateTime objects?
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
Then you can do:
if (dateToCompare1 < dateToCompare2)
Or whatever comparison operator you want.
Edit: from your comment, I think you would like use only dates that are later (or equal to?) one year from now. And so you would do:
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
if (date >= DateTime.Now.AddYears(1) {
// Do whatever you want with the "kept" dates
}
Assuming you have a string:
string strDate1 = "09/06/2011";
string strDate2 = "09/06/2011";
DateTime date1 = DateTime.Parse(strDate1);
DateTime date2 = DateTime.Parse(strDate2);
Then compare them.
Related
I am trying to convert a string into DateTimeOffset. here is an example of my string 2017/010/23:51:50 2017 represents year 010 represent day of the year and 23:51:50 is time.
I am trying in below way but it returns me 0001-01-01 00:00:00.0000000 +00:00 always no mater the input is.
My code
DateTimeOffset DateTime;
string year = ("2017/010/23:51:50");
DateTimeOffset.TryParse(year, out DateTime);
Any suggestion please?
Update
For simplicity I did not linger my question. My date time I am getting year (2017 it could be 2002, 2001 ) from name of a .txt file and day and time (010/23:51:50 some has offset and some content don't) from the content of that .txt file. So my input is not always same. hope this clarifies
First split the string by / and then use the dayOfTheYear value and the year to obtain the year/month/date. Next split the time parameter and use it to obtain TimeSpan and add it to the previously obtained date. Next, simply parse your newly obtained date to DateTimeOffset. This code should work:
string year = ("2017/010/23:51:50");
var date = year.Split('/');
var timeSpanVal = date[2].ToString().Split(':').Select(x=>Convert.ToInt32(x)).ToList();
TimeSpan ts = new TimeSpan(timeSpanVal[0], timeSpanVal[1], timeSpanVal[2]);
DateTime newDate = new DateTime(Convert.ToInt32(date[0]), 1, 1).AddDays(Convert.ToInt32(date[1]) - 1)+ts;
DateTimeOffset.TryParse(newDate.ToString(), out DateTime);
Looking through the date and time formats, I don't think you can parse the format Year/JulianDay/Time. What you can do is split the string into parts and then add the days to the year
string[] parts = year.Split('/');
DateTime dt = new DateTime(int.Parse(parts[0]), 1, 1);
dt = dt.AddDays(int.Parse(parts[1]) - 1).Add(TimeSpan.Parse(parts[2]));
In my C# project I need system date time to another specific date time format.
My system datetime format is like "15/03/2017 9:25 AM" --->that can be changed according to computer wich my program run.
But I need to parse that datetime format to another date time format something like "2017-03-15 9:25 AM"----> save date in SQL datebase accept this format only.
I need Assign this to variable to Datetime Variable not need save in String variable.
I tried this code but not working
string datetimesss = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
It returns
// value of datetimesss="2017-03-15 09:33:25"
Then i parse again to date time format
DateTime dates = DateTime.Parse(datetimesss);
It returns
// value of dates ="15/03/2017 9:42:43 AM"
Convert back to my computer datetime format .How can I convert any datetime format to DateTime "yyyy-MM-dd hh:mm:ss"
Thank You!
You should avoid strings and just keep your data in DateTime variables. ADO.Net already knows how to translate between .NETs DateTime and SQL Server's datetime - and neither of these has a format (both of them, internally, are just numbers. .NETs DateTime is a count of 100ns intervals since 01/01/0001. SQL Server's datetime is a count of whole and fractional days since 01/01/1900).
Something like:
var updateCommand = new SqlCommand(
"UPDATE [User] SET Last_loign_date =#LastLoginDate"
,conn); //Assume conn is an SqlConnection object
updateCommand.Parameters.Add("#LastLoginDate",SqlDbType.DateTime).Value = DateTime.Now
or, in the alternative, why not use the database server time rather than passing it:
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date =current_timestamp";
If sql server language is set as us-english then your date - > '15/03/2017 9:25 AM' will be considered as text and converting into date will not give correct results. You need create date based on day,month and year from your given date by using string functions. Use the below code to get required output :
declare #date varchar(30) = '15/03/2017 9:25 AM'
select cast(left(parsename(replace(#date,'/','.'),1),4) +
parsename(replace(#date,'/','.'),2) +
parsename(replace(#date,'/','.'),3) as datetime) +
ltrim(stuff(parsename(replace(#date,'/','.'),1),1,4,''))
Finaly I got the point,
I parse DateTime to String
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date ='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "'";
In SQl database "Last_loign_date" is datetime format.
this may not correct, but this worked for me.
thanks!
I have the following simple example:
string dt = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
I can't change the DateTime.Now, but I can change datetime format yyyy-MM-dd hh.mm.ss. Following this example the result must be today's date, but I need to get yesterday's date with the same parameters except day (year, month, hours, minutes and seconds). E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it possible to use some "-" operator or something else inside the datetime format to achieve the result?
If you want yesterday's date, you can do this
string dt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh.mm.ss");
DateTime.AddDays() lets you add number of days, positive for future date, negative for past date.
E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it
possible to use some "-" operator or something else inside the
datetime format to achieve the result?
No, it's not possible inside the DateTime format. you can not change any thing. Because it is only for define format of the Date to display in string format. Any addition or subtraction can only be done before converting it to string format as suggested by "Arghya C".
Can you explain your limitation so we can solve your problem.
If you can only influence the date time pattern, than use the roundtrip format and parse the returning string back to a date time, add the calculation and format it into the desired format:
var dateTimeString = badLibrary.GetDateTime("o");
var dateTime = DateTime.Parse(dateTimeString, null, DateTimeStyles.RoundtripKind);
var newDateTime = dateTime.AddDays(-1);
return newDateTime.ToString("yyyy-MM-dd hh.mm.ss");
Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..
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.