本篇文章是对使用DateTime的ParseExact方法实现特殊日期时间的方法进行了详细的分析介绍,需要的朋友参考下
今天遇到一个特别的需求,需要从下面的字符串中转换成一个DateTime对象:

[07-13 15:50:42]

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

主要问题是这个时间不是标准的时间,而是自定义的格式,即开头是月-日,然后是时间。

使用最常用的DateTime.Parse(string dateTimeStr)无法转换,问题就在于这个自定义格式上。

搜索了之后,我找到了下面的方法:

public static DateTime ParseExact(
string s,
string format,
IFormatProvider provider
)

使用例子如下:

var dateTimeStr = "07-13 15:50:42";
var dateTime = DateTime.ParseExact(dateTimeStr, "MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

使用效果如下:

 

如果你使用的其它特殊语言,比如美国或者日文啥的,最后的参数你可能需要获取下对应的Culture。

注意:

•如果dateTimeStr或者format 是null,会抛出ArgumentNullException异常。

•如果dateTimeStr或者format 是空字符串,则抛出FormatException异常。

 

 

 

相关资料:

http://hi.baidu.com/tracyjay/item/9c3208ab3bd82fff14329bac

http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

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.

public static DateTime ParseExact(
string s,
string format,
IFormatProvider provider
)
Parameters
s
Type: System.String
A string that contains a date and time to convert.
format
Type: System.String
A format specifier that defines the required format of s. For more information, see the Remarks section.
provider
Type: System.IFormatProvider
An object that supplies culture-specific format information about s.
Return Value
Type: System.DateTime
An object that is equivalent to the date and time contained in s, as specified by format and provider.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Exception

Condition

ArgumentNullException

s or format is null.

FormatException

s or format is an empty string.

-or-

s does not contain a date and time that corresponds to the pattern specified in format.

-or-

The hour component and the AM/PM designator in s do not agree.

 

The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the formatparameter. It also requires that the <Date> and <Time> elements of the string representation of a date and time appear in the order specified by format, and that shave no white space other than that permitted by format. If format defines a date with no time element and the parse operation succeeds, the resulting DateTimevalue has a time of midnight (00:00:00). If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date ofDateTime.Now.Date.

If s does not represent a time in a particular time zone and the parse operation succeeds, the Kind property of the returned DateTime value isDateTimeKind.Unspecified. If s does represent the time in a particular time zone and format allows time zone information to be present (for example, if format is equal to the "o", "r", or "u" standard format specifiers, or if it contains the "z", "zz", or "zzz" custom format specifiers), the Kind property of the returned DateTimevalue is DateTimeKind.Local.

The format parameter is a string that contains either a single standard format specifier, or one or more custom format specifiers that define the required format of s. For details about valid formatting codes, see Standard Date and Time Format Strings or Custom Date and Time Format Strings.

Note

If format is a custom format pattern that does not include date or time separators (such as "yyyyMMdd HHmm"), use the invariant culture for the providerparameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".

The particular date and time symbols and strings (such as names of the days of the week in a particular language) used in s are defined by the provider parameter, as is the precise format of s if format is a standard format specifier string. The provider parameter can be any of the following:

If provider is null, the CultureInfo object that corresponds to the current culture is used.

Notes to Callers

In the .NET Framework 4, the ParseExact method throws a FormatException if the string to be parsed contains an hour component and an AM/PM designator that are not in agreement. In the .NET Framework 3.5 and earlier versions, the AM/PM designator is ignored.

 

using System;
using System.Globalization; public class Example
{
public static void Main()
{
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture; // Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
} // Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
} // Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
} // Parse date and time with offset but without offset's minutes.
// Should throw a FormatException because "zzz" specifier requires leading
// zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
} dateString = "15/06/2008 08:30";
format = "g";
provider = new CultureInfo("fr-FR");
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
}
}
// The example displays the following output:
// 06/15/2008 converts to 6/15/2008 12:00:00 AM.
// 6/15/2008 is not in the correct format.
// Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
// Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
// 15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

使用DateTime的ParseExact方法实现特殊日期时间的方法详解(转)的更多相关文章

  1. ORACLE——日期时间格式化参数详解 之一

    2.日期格式化参数详解 2.1 -/,.;: 指定返回字串分隔符 SQL> select to_char(sysdate,'yyyy.mm.dd') from dual; TO_CHAR(SYS ...

  2. ORACLE——日期时间格式化参数详解 之三

    2.20 Y,YYY 返回有逗号分隔显示的年 SQL> select to_char(SYSTIMESTAMP,'Y,YYY') from dual; TO_CHAR(SYSTIMESTAMP, ...

  3. ORACLE——日期时间格式化参数详解 之二

    2.8 DD 指定日期在当月中第几天(范围:1-31) SQL> select to_char(sysdate,'DD YYYY-MM-DD PM hh24:mi:ss ') from dual ...

  4. Python实用日期时间处理方法汇总

    这篇文章主要介绍了Python实用日期时间处理方法汇总,本文讲解了获取当前datetime.获取当天date.获取明天/前N天.获取当天开始和结束时间(00:00:00 23:59:59).获取两个d ...

  5. JavaScript中的内置对象-8--4.date对象中-获取,设置日期时间的方法; 获取,设置年月日时分秒及星期的方法;

    学习目标 1.掌握创建日期对象的方法 2.掌握date对象中获取日期时间的方法 3.掌握date对象中设置日期时间的方法 如何创建一个日期对象 语法:new Date(); 功能:创建一个日期时间对象 ...

  6. java多态性方法的重写Overriding和重载Overloading详解

    java多态性方法的重写Overriding和重载Overloading详解 方法的重写Overriding和重载Overloading是Java多态性的不同表现.重写Overriding是父类与子类 ...

  7. 第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解

    第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解 一.    引言 上两节介绍了构造方法的语法及参数,说明了构造方法是Python的类创建实例后首先执行的方法,并说明如果类 ...

  8. C# 如何获取日期时间各种方法

    我们可以通过使用DataTime这个类来获取当前的时间.通过调用类中的各种方法我们可以获取不同的时间:如:日期(2019-01-09).时间(16:02:12).日期+时间(2019-01-09 16 ...

  9. JS格式化日期时间的方法

    //格式化时间的方法 function format(fmt, date) { var o = { "M+": date.getMonth() + 1, //月份 "d+ ...

随机推荐

  1. DBCC--SQLPERF

    ​提供所有数据库的事务日志空间使用情况统计信息.也可以用于重置等待和闩锁的统计信息. 语法: DBCC SQLPERF ( [ LOGSPACE ] | [ "sys.dm_os_latch ...

  2. 设计模式之命令模式(Command Pattern)

    一.什么是命令模式? 命令模式,封装了方法调用细节,以解耦请求者与执行者,具体流程如下: 1.从请求者(客户)的角度看 请求者(客户)发出请求 -> 调用者(系统)构造命令对象封装请求 -> ...

  3. WebAPI的AuthorizeAttribute扩展类中获取POST提交的数据

    在WEBAPI中,AuthorizeAttribute类重写时,如何获取post数据是个难题,网上找资料也不好使,只能自己研究,通过研究发现,WEBAPI给了我们获取POST数据的可能,下面介绍一下: ...

  4. .netcore与vue的学习笔记001

    1.dnc的js引用 需要引用的js文件要放在解决方案下的wwwroot目录下.否则将无法获取到指定js文件,出现404错误 2.vue的相关运用 0)通过new Vue并传入object来实例化一个 ...

  5. XML Web Service架构图

  6. Reddit CEO亲自诠释内容审核的无奈

    本文由  网易云发布. 导语:继数据泄露危机之后,Facebook将会雇用数千名新员工来负责新的验证系统,这个系统将首先在美国广告客户中生效,并将在未来几个月内涵盖其他国家.与此同时,如何让自己的社区 ...

  7. 918. Maximum Sum Circular Subarray

    Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...

  8. django 使用其自带的验证系统 进行用户名有效性验证 登录状态验证 登入操作 登出操作

    from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, l ...

  9. poj3026

    Borg Maze Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 12952   Accepted: 4227 Descri ...

  10. sql语句应考虑哪些安全性?

    (1)少使用root账户,应该为不同的动作分配不同的账户: (2)sql执行出错后,不能把数据库中显示的出错信息,直接展示给用户.防止泄露服务器和数据库相关信息: (3)防止sql注入,对特殊字符进行 ...