Change from datetime to date in the session variable using c# - c#

txtdob.Text = Session["DOB"].ToString();
It is displaying both date and time,I need only date to be printed,Is there any type of code that makes to display only date within the code i have mention above.?
If i execute the above code it gives the date format as
9/9/2013 12:00:00 AM
But i just need 9/9/2013
In the database DOB has a datatype of DateTime.
I tried with every line of code you have suggested but its giving error as Specified cast is not valid
session["DOB"] is stored as
Session["DOB"] = ds.Tables["login_det"].Rows[0].ItemArray[5].ToString();
Do i need to change this?

If Session["DOB"] is a DateTime instance you could specify the format:
txtdob.Text = ((DateTime)Session["DOB"]).ToString("dd/MM/yyyy");
If it is not DateTime, but a string, then you will have to modify the code that is storing this value into the session so that it either stores the DateTime or it formats the string the way you want it to be.

Try this:
txtdob.Text = Convert.ToDateTime(Session["DOB"].ToString()).Date.ToShortDateString();
OR
txtdob.Text = Convert.ToDateTime(Session["DOB"].ToString()).ToString("dd/MM/yyyy");

Try this
txtdob.Text = Convert.ToDateTime(Session["DOB"]).ToString("dd/MM/yyyy");
or you can find more formats here

Related

How to convert this date 2017-07-09T17:50:21.000-0500 | C#

when i run the below code,
string dt = "2017-07-09T17:50:21.000-0500";
DateTime date = Convert.ToDateTime(dt);
it gives me output as
7/10/2017 4:20:21 AM
where as i want my output to be
2017-07-09 17:50
update
the code #alexander-petrov gave worked
string dt = "2017-07-09T17:50:21.000-0500";
string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");
gives output
2017-07-09 17:50
but on inserting the same to database it is adding +5 hrs to the time and inserting as
2017-07-09 22:50
This is a Round-Trip format of a DateTime specified with a DateTimeKind.Local kind.
You need to decide if your program needs to be aware of time zones or not.
You could try parsing it while supplying the System.Globalization.DateTimeStyles.RoundtripKind or System.Globalization.DateTimeStyles.AdjustToUniversal parameter to the Parse method.
If you want take offset into account then use DateTimeOffset type.
string dt = "2017-07-09T17:50:21.000-0500";
DateTimeOffset date = DateTimeOffset.Parse(dt);
// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);
// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);
I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:
DECLARE #stringDate VARCHAR(30);
SELECT #stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE #xmlDate XML;
SELECT #xmlDate = CAST('' AS XML);
SELECT #xmlDate.value('xs:dateTime(sql:variable("#stringDate"))', 'datetime');
Results:
2017-07-09 22:50:21.000
Try:
string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

Convert Date datatype from SQL Server to ToShortDateString in C#

I'm trying to convert the date output to a ToShortDateString in my text box from a DataTable. Currently it's showing "2/4/1965 12:00:00 AM".
Here's the code:
txtDOB.text = dataTable.Rows[0][7].ToString().Trim();
Any idea?
Use the DataRow extension method Field to cast it to the correct type DateTime. Then you can use DateTime.ToShortDateString:
txtDOB.text = dataTable.Rows[0].Field<DateTime>(7).ToShortDateString();
You can also use DateTime.ToString:
txtDOB.text = dataTable.Rows[0].Field<DateTime>(7).ToString("d");
Try this:
DateTime Temp = (DateTime) dataTable.Rows[0][7]
txtDOB.text = Temp.ToShortDateString();
I'd try a direct cast first:
var date = (DateTime)dataTable.Rows[0][7];
txtDOB.Text = date.ToShortDateString();
If the database is storing the field as an actual date, that is the best way to get it back.
Try this :
string date = dataTable.Rows[0][7].ToString().Trim();
txtDOB.text = date.Split(' ')[0];

c# converting datetime in a different culture

I'm trying to convert a german DateTime value into a french DateTime object.
The value of my item called "_dateFacture" is "08.07.2015 17:23:01"
var stringdate = _dateFacture.ToString(new CultureInfo("fr-FR")); //d2 = "08/07/2015 17:23:01"
var testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR")); // testfinal = "08.07.2015 17:23:01"
How is it possible for the object testfinal to get a value like that ?
If you had declared the datatype with each variable, instead of using var, it would have been easier to spot.
string stringdate = _dateFacture.ToString(new CultureInfo("fr-FR"));
DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR"));
testfinal is a DateTime, not a string.
When you look at it in a debugger or view, testfinal is converted to a string using DateTime.ToString() which uses the current culture (which presumably displays dates with a dot).
What you saw is just a representation issue. They are the same DateTime values.
DateTime doesn't have any implicit format. And it doesn't have any IFormatProvider. It just a date and time values. Format is only a subject when you try to get it's textual representation.
I strongly suspect you see this in your debugger or something;
Your stringdate is a string, but your testfinal is a DateTime. If you wanna save your datetime values in your database, don't save their string representations. Put your datetime values directly to your parameterized queries.
Read: Bad habits to kick : choosing the wrong data type
if you want to store testfinal as a datetime, you just need to make sure your var is in fact a DateTime.
DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR"));
To show it you can use a format in the ToString function:
string formattedDate = testfinal.ToString("dd.MM.yyyy HH:mm:ss");
//now your formattedDate will be "08.07.2015 17:23:01"

how to compare the time and date using mysql and c#

I have a table logout with columns
logout_id
logout_datetime values format like this(2011-09-08 11:09:09)
and i want to compare the logout_datetime with today date and time also....
for that i have done like this....
string dtStartString = DateTime.Today.ToString("yyyy-MM-dd");
string timeonly = DateTime.Now.ToShortTimeString();
string sql = #"select logout_id";
sql+= string.Format("where logout_datetime = '{0}'",dtStartString );
but it will compares only date in logoutdatetime ,its wrong i want to compare the time also
how can i do this..
would any one pls help on this...
Of course your code is only comparing the date because you are passing only dtStartString which does not have a time part.
try to pass this:
string dtStartString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Use Parameters.
string sql = "select logout_id from TableName
where logout_datetime=#logout_datetime";
...
cmd.Parameters.Add("#logout_datetime",MySql.Data.MySqlClient.MySqlDbType.Datetime)
.Value=DateTime.Now; // you may assign any value of DateTime type.
You could use the date-format, or extract function.
You should read more about date time functions

how can i assign only year say 2011 in a datetime variable in c#

I have a asp Text box as
where the user will fill only a year value, For this value I have Datetime type Property in c# application and Date type column in DB. So I want to convert that txtYear.Text to DateTime But it will only hold and/or show the year. Please help me in this situation.
A DateTime object will always hold a complete DateTime value, you can't use it to store a year only. (what use would that be anyway?) Besides, the datatype of a "year" is int, not DateTime.
So, I'd like to suggest changing your property to datatype int, both in your code and database.
To display just the year use the format "yyyy".
string s = "2011";
DateTime d = new DateTime(int.Parse(s), 1, 1);
Console.WriteLine(d.ToString("yyyy"));
Console.WriteLine(d);
You have to specify the format of the DateTime value you are manipulating:
String dateTimeFormat = "yyyy";
To show only a part of the DateTime value use the following:
dateTimeValue.ToString(dateTimeFormat);
To read a String value that represents a year into a DateTime use the following:
DateTime.ParseExact(stringValue, dateTimeFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact Method (String, String, IFormatProvider) converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime.ToString Method converts the value of the current DateTime object to its equivalent string representation.
Rather than applying any string manipulating function make use of Year property. Check the documentation on the msdn by visiting below link.
DateTime.Year Property
A DateTime always has a full date component. When you create the DateTime instance, you'll need to assign a month and day, but you can ignore them in your usage.
DateTime d = new DateTime(int.Parse(txtYear.Text, 1, 1);
txtYear.Text = d.ToString("yyyy");
Even better would be not to use a DateTime but just use int. If you have only a year, you only need an int.
i assume the text box name is txYear
DateTime dt = new DateTime (Convert.ToInt32(txYear.text),1,1)
save this dt value in database
If you want only the year, why don't you make it of type smallint?
Anyway if you do really want to make it an year,
DateTime x = new DateTime(Convert.ToInt32(txtYear.text), 1, 1);
But make sure you validate that txtYear.text actually does have a valid year.
That is how I did and it worked.
string format = "yyyy";
var CurrentYear = DateTime.Now.ToString(format);

Categories

Resources