Checking if String is a proper date and insert it into database - c#

I store in database value of date.
I display the current date in format:
textBoxTradeDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
I want insert this date into database. How to check if it is proper value? I don't want use Regular Expression and I need to save this textBoxTradeDate.Text in database. Also, the user must be able to change this date, so I can't store DateTime.Now and only display date part.
I don't want use Calendar tool.

Use TryParseExact, so that you can specify the date format:
DateTime tradeDate;
bool ok = DateTime.TryParseExact(
textBoxTradeDate.Text,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out tradeDate
);
if (ok) {
// correct date, so you can put it in the database
} else {
// incorrect format, so tell the user
}

You can use DateTime.TryParse().
But you should ensure that you specify the expected date format if there is the possiblity of a problem.
string datestr = "2001-01-01";
DateTime date;
if (DateTime.TryParse(datestr, out date)) {
//write date to db
} else {
//throw an error
}

so I cant store DateTime.Now and only display date part.
SQL Server's date type with mapped DateTime type of .NET Framework. That's why you should insert your datetime value directly date typed column and this column saves only date part of it.
Since you always passing your formatted DateTime.Now to textBoxTradeDate.Text property, you can just pass this DateTime.Now value directly your parameterized insert query.
If you wanna check your textBoxTradeDate.Text is a valid DateTime, there are DateTime.Parse, DateTime.TryParse, DateTime.ParseExact and DateTime.TryParseExact methods which they are exactly what this for.
string s = textBoxTradeDate.Text;
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// You have a valid datetime.
}

Related

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

how to compare datetime value from database with textbox datetime value

I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.

Unable to convert textbox(dd/MM/yyyy) date to datetime format

I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format". I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same
First of all, a DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format.
I strongly suspect you save your DateTime values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass your DateTime values directly to your parameterized queries instead of their string representations. Anyway..
For;
DateTime timeIn = Convert.ToDateTime(txtdate.Text);
Convert.ToDateTime(string) method uses DateTime.Parse method with your CurrentCulture settings. That means if your string isn't a standard date and time format of your CurrentCulture your code throws FormatException. I guess dd-MM-yyyy is not a standard date and time format of your CurrentCulture.
For;
DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
When you use DateTime.ParseExact, your string and format should match exactly.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case; they are not ("26-11-2014" and "yyyy-MM-dd"). Use dd-MM-yyyy format instead.
DateTime time1 = DateTime.ParseExact(txtdate.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture);
Then you can generate the format from your time1 like;
time1.ToString("yyyy-MM-dd"); // A string formatted as 2014-11-26
For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
You can use this
var dateAndTime=Convert.ToDateTime(Txttradedate.Text).ToString("ddmmyyyy");

Error while converting string to DateTime after publishing to web server

I am using below code
DateTime dtt=new DateTime();
dtt = Convert.ToDateTime(FromDate);
// DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error
con = new MySqlConnection(conString);
con.Open();
for (int i = 1; i <= TotalDays; i++)
{
string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
cmd7.ExecuteNonQuery();
dtt = dtt.AddDays(1);
}
This code is in one of my webservice which I am using for iPhone application.
here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days
I need to add day to dtt.
It is working fine on local host with dtt value 15-11-2011 00:00:00
but when I published it,it gives error
String was not recognize as valid DateTime
This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.
You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.
Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.
EDIT: To parse from a fixed format of dd-MM-yyyy I would use:
DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out value))
{
// Value will now be midnight UTC on the given date
}
else
{
// Parsing failed - invalid data
}
What are you culture settings on your local machine and on the server?
The DateTime conversion is dependent on the current culture - dates are written quite differently in different countries.
One way to make the conversion "predictible" is to use the invariant culture:
DateTime dtt = Convert.ToDateTime(FromDate, CultureInfo.InvariantCulture);
the server date format may be in mm/dd/yyyy and you are trying to pass dd/mm/yyyy
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;
foreach (var dateValue in dateValues) {
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.
Check this for more details
Log (or otherwise provide feedback to yourself) what FromDate is. Maybe it's empty?
May the Language Settings on the Server are different so it does not recognize the dd-MM-yyyy - try using DateTime.ParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture);

How to Convert Date Object with Format "MM/dd/yy hh:mm:ss tt" to DateObject with Format "dd/MM/yy

I have googled alot and tried lot of solutions but nothing is working for me.For Ex i Have tried below :
public static DateTime ParseDateToSystemFormat(DateTime date)
{
IFormatProvider culture = new CultureInfo("en-GB", true);
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
return Convert.ToDateTime(dt,culture);
}
If anyone have solved this please let me know.
Date objects do not have formatting associated to them - you only use formatting for display.
When it is time to display the DateTime object, use either custom or standard format strings to format the display to your liking.
What you are doing here:
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
Is rather strange - you are getting a specific string representation of your DateTime - date.ToString("dd/MM/yyyy"), then parsing that string back to a DateTime object. A bit of a long way to say DateTime dt = date;, with clearing out the hours/minutes/seconds data.
If you simply want the date portion of a DateTime, use the Date property. It produces:
A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
The internal representation of a DateTime is always the same. There is no formatting attached to a DateTime object.
If it is only a display problem, then convert the DateTime to a string and display that string. You already know how to do it: Using ToString and specifying the format you want to have.

Categories

Resources