开发者

How to divide DATETIME column value into day, month and year in C#

I have a DATETIME column in my database. I need to get the value and divide it into 3 variables each having the year, month and day

I am trying to do

dataadapter.Fill(dataset, "tablename");
string x;  
foreach(DataRow dd in dataset.Tables["tablename"].Rows)
{
    x = dataset.Tables["tablename"].Rows[0]["date1"].ToString();
}

here x is holding the whole of m/dd/yr and time but how can I now have 3 variables which can store开发者_运维知识库 the month in a, year in b and day in another variable c?


How about this.

int year, month, day;
DateTime all;

if(DateTime.TryParse(dataset.Tables["tablename"].Rows[0]["date1"], out all)
{
    year = all.Year;
    month = all.Month;
    day = all.Day;
}


foreach(DataRow dd in dataset.Tables["tablename"].Rows)
{
    var date = DateTime.Parse(dd["date1"].ToString());
    int day = date.Day;
    int month = date.Month;
    int year = date.Year;
    // Do something with it
}


DateTime dt = DateTime.Parse(x);
int day = dt.Day;
int month = dt.Month;
int year = dt.Year;


DateTime x;  
foreach(DataRow dd in dataset.Tables["tablename"].Rows)
{
  x = DateTime.Parse(dataset.Tables["tablename"].Rows[0]["date1"].ToString());
}

Then you don't need to keep 3 separate variables, you'll have x as a DateTime so you can just call x.Year, x.Month, x.Date (You could still assign it to 3 different variables if you want)


I guess that the best way would be to create a SQL query that will get desired date components for you, then fill the datatable from that query, not from the table itself.

That way, you'll learn some SQL date handling functions by the way... :)


What is the datatype of the field in the database?

If your database field is a string then you'll have to parse it, otherwise you can just cast it to a DateTime:

// Parse it (be careful, could throw an exception)
DateTime date = DateTime.Parse(dataset.Tables["tablename"].Rows[0]["date1"].ToString());

// Or cast it:
DateTime date = (DateTime)dataset.Tables["tablename"].Rows[0]["date1"];

// Then pull out the values you wish to use from the date object
int months = date.Month;
int day = date.Day;
int year = date.Year;


Some options:

  1. You can bust it up into its component parts in SQL:

    select yyyy = year(  t.some_datetime ) , -- integer year
           mm   = month( t.some_datetime ) , -- integer month (1-12)
           dd   = day(   t.some_datetime ) , -- integer day (1-31)
    from dbo.some_table t
    
  2. You can convert it a fixed length ISO 8601 string (easy to parse, collates properly), again in SQL:

    select charDate = convert(char(10),t.some_datetime,126) -- 'yyyy-mm-dd'
    from dbo.some_table t
    

    Parsing out the components is an easy substring operation.

  3. As noted by others: Just select the datetime value. ADO.Net maps that to System.DateTime.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace ConsoleApplication4
    {
        class Program
        {
          static void Main( string[] args )
          {
            string myConnectString = GetConnectionString() ; // your connect string here!
            using ( SqlConnection dbConnection = new SqlConnection( myConnectString ) )
            using ( SqlCommand    sql          = dbConnection.CreateCommand() )
            {
              sql.CommandType = CommandType.Text ;
              sql.CommandText = @"
    select t.some_datetime
    from dbo.some_table t
    " ;
              dbConnection.Open() ;
              using ( SqlDataReader reader = sql.ExecuteReader() )
              {
                while ( reader.Read() )
                {
                  DateTime someDateTime = reader.GetDateTime(0) ;
                  process( someDateTime.Year , someDateTime.Month , someDateTime.Day ) ;
                }
              }
              dbConnection.Close() ;
            }
    
            return ;
          }
    
          private static void process( int p , int p_2 , int p_3 )
          {
            throw new NotImplementedException();
          }
    
        }
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜