Reputation: 1435
I have a string
string str = "26/01/2015";
I need to convert it into datetime as 2015-01-26 00:00:00.000
so that I can store it in database.
What I have tried so far is
DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.InvariantCulture)`
and I am getting the value as '26/01/2015 12:00:00 AM'
.
But I need it as 2015-01-26 00:00:00.000
.
Is it possible? Any help appreciated
Upvotes: 0
Views: 2233
Reputation: 34421
There is no need to worry about converting a datetime if you use a parameter to store the data like the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication58
{
class Program
{
static void Main(string[] args)
{
string connStr = "Enter Your Conneciton String Here";
string SQL = "INSERT INTO Table1 (Time_Col) VALUES ('@MyTime');";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.Add("@MyTime", SqlDbType.DateTime);
DateTime now = DateTime.Now();
cmd.Parameters["@MyTime"].Value = now;
cmd.EndExecuteNonQuery();
}
}
}
Upvotes: 0
Reputation: 169
once you have the DateTime object you could just update your database because it's the most accurate one. What matter to you on the output is when you retrieve it back from database, it is datetime object then do your .ToString to format it.
Upvotes: 1
Reputation: 1336
You convert it to string and pass the parameters to ToString() function as described in these standard as per your need.
You can use
DateTime d = DateTime.Now;
d.ToString("U");
Upvotes: 0
Reputation: 7187
You can try this:
string outputFormat = DateTime.ParseExact("26/01/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss.fff");
But I think it is better to keep this as a DateTime to write it to the database, not string
Upvotes: 0
Reputation: 23087
You need to convert it to string like this (if you want it as formatted string):
var parsed = DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var formatted = parsed.ToString("yyyy-MM-dd HH:mm:ss.fff");
I presume you want to have formatted datetime string.
Upvotes: 0