如何将数组元素格式转换为特定的日期时间 [英] How to convert array element format to specific datetime

查看:253
本文介绍了如何将数组元素格式转换为特定的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

I have the following code:

foreach (var element in onlyIn1) {
    for (int i = 0; i < element.ItemArray.Count(); i++ )
    {
        System.Type type = element[i].GetType();
        if (type == typeof(DateTime))
            element[i] = DateTime.ParseExact(element[i].ToString(), "MMddyyyy HH:mm:ss.fff", null);

    }



这给了我以下错误。我正在尝试遍历数组的每个元素,找到它的数据类型并使用我需要的格式重新分配它。我是否正确分配了Array元素?



base {字符串未被识别为有效的DateTime。} System.Exception {System.FormatException}

推荐答案

这只是意味着您在MMddyyyy HH:mm:ss.fff所期望的字符串内容和时间格式之间存在不匹配。您没有显示输入字符串的示例,因此请自行排序。这一点都不难。请仔细阅读:

http:// msdn .microsoft.com / zh-cn / library / az4se3k1(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/8kb3ddd4(v = vs.110)的.aspx [< a href =http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]。



不要忘记当前的线程文化(继承自配置OS用户帐户的默认文化)可能会影响它。其中一个案例是你想要长时间使用长格式,在不同文化中有不同的名称。为了保证正确的解析,你可以1)使用中性文化,2)使用特定的文化 ParseExact (或者更好的是, TryParseExact ),3)为调用方法的线程选择所需的文化。

这是 ParseExact 方法,它允许指定文化(最后一个参数): http://msdn.microsoft.com/en -us / library / w2sa9yss%28v = vs.110%29.aspx [ ^ ]。



对于一个帖子,你可以选择当前的文化: http://msdn.microsoft.com/en -us / library / system.threading.thread.currentculture(v = vs.110).aspx [ ^ ]。



顺便说一下,另见: http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture( v = vs.110).aspx [ ^ ]。



-SA
It simply means that you have a mismatch between the string content and time format you expected by "MMddyyyy HH:mm:ss.fff". You did not show the sample of the input string, so please sort it out by yourself. This is not difficult at all. Please review thoroughly:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx[^].

Don't forget that the current thread culture (inherited from the default culture configured the an OS user account) may affect it. One of the cases is when you want to use long format for months, which have different names in different cultures. To guarantee correct parsing, you can 1) use neutral culture, 2) use specific culture for ParseExact (or, better, TryParseExact), 3) choose desired culture for a thread where you method is called.
This is the ParseExact method which allows to specify the culture (last parameter): http://msdn.microsoft.com/en-us/library/w2sa9yss%28v=vs.110%29.aspx[^].

For a thread, you can choose the current culture: http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture(v=vs.110).aspx[^].

By the way, see also: http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture(v=vs.110).aspx[^].

—SA


您似乎误解了DateTime是什么。 DateTime没有内在格式。

由于您已经确定该值是DateTime,因此无需做任何事情。



什么你想完成什么?
You seem to misunderstsand what a DateTime is. A DateTime has no intrinsic format.
As you have already determined that the value is a DateTime, there is nothing to do.

What are you trying to accomplish?


谢谢大家的回复。我发现c#中的datetime与SQL datetime不同。尽管datatable保存了毫秒值,但是在将其插回到SQL数据库时,它会丢失它并放置000像这样的2014-04-15 13:49:05.000。我必须找到一种更好的插入日期时间字段的方法。所以我写了一个方法来选择数据(动态构建它),把它放到select语句中插入但如果字段是datetime ,它会把那个字符串转换成我想要的特定格式,在我的case,包括毫秒。然后我将它插入db并瞧。这是方法。



这是方法调用:

Thank you guys for all the replies. I discovered that datetime in c# is different from SQL datetime. Although datatable holds the milliseconds value, while inserting it back to SQL database, it looses it and places 000 like this 2014-04-15 13:49:05.000. I had to find a better way of inserting datetime field. So I wrote a method that would select the data (build it dynamically), put it into select statement for insert but if the field is datetime, it will convert that string to specific format I wanted, in my case, include milliseconds. Then I insert it to db and voila. Here is the method.

This is the method call:
bRetVal = ExecuteSQL(SQLSystems.SQL_InsertRecordTo_Server(startRow, table, tableName, out rowsCompleted, out bCompleted));




public static string SQL_InsertRecordTo_Server(int startRow, DataTable table, string tableName, out int rowsCompleted, out bool bCompleted)
{

    bool bDone = false;
    StringBuilder strSQL = new StringBuilder();
    strSQL.AppendFormat("INSERT INTO {0} (", tableName);
    rowsCompleted = 0;
    bCompleted = true;
    for (int i = 0; i < table.Columns.Count; i++) {
        strSQL.AppendFormat("{0}", table.Columns[i].ColumnName);
        if (i < table.Columns.Count - 1) {
            strSQL.Append(","); ;
        }

    }
    strSQL.AppendFormat(") "); ;
    for (int j = startRow; j < table.Rows.Count; j++)
    {
        rowsCompleted++;
        strSQL.AppendFormat(" SELECT  ");
        for (int i = 0; i < table.Columns.Count; i++)
        {
            if(!(string.IsNullOrEmpty((table.Rows[j][i]).ToString()))) {
                if(table.Rows[j][i].ToString().ToLower().Equals("true")) {
                   strSQL.AppendFormat("'1'");
                } else if(table.Rows[j][i].ToString().ToLower().Equals("false")) {
                    strSQL.AppendFormat("'0'");
                } else {
                    if (table.Rows[j][i].GetType() == typeof(DateTime))
                        strSQL.AppendFormat("'{0}'", String.Format("{0:MM/dd/yyyy HH:mm:ss.fff}", table.Rows[j][i]));
                    else
                        strSQL.AppendFormat("'{0}'", ((table.Rows[j][i]).ToString()).Replace("'", "''"));
                }
            } else {
                if(table.Rows[j].IsNull(i)) {
                    strSQL.AppendFormat(" NULL");
                } else {
                     strSQL.AppendFormat(" ''");
                }
            }
            if (i < table.Columns.Count - 1) {
                strSQL.Append(","); ;
            }
        }
        if ((j == table.Rows.Count - 1) || ((j - startRow) == MAX_ROWS - 1)) {
            strSQL.AppendFormat(";");
            if (j != table.Rows.Count - 1) {
                bDone = true;
            }
        } else {
            strSQL.AppendFormat(" UNION ALL ");
        }
        if (bDone) {
            bCompleted = false;
            break;
        }
    }
    return (strSQL.ToString());
}


这篇关于如何将数组元素格式转换为特定的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆