将第一天的字符串转换为日期时间

时间:2018-09-03 07:59:52

标签: c# datetime

我正在寻找一种能够转换这样的日期字符串的方法:

from tkinter import *

class Buttons:
    def __init__(self, row, column, frame):
        self.row = row
        self.column = column
        b = Button(frame).grid(row = self.row, column = self.column)

tk = Tk()
b1 = Buttons(row = 1, column = 1, frame = tk)
tk.mainloop()

或者这个:

"1st Oct 2018" => 2018-10-01

相当于"10th Mar 2015" => 2015-03-10 ,格式为string。我尝试了以下代码,但是没有运气:

yyyy mm dd

3 个答案:

答案 0 :(得分:4)

除了雏菊的精彩回答:

<script type="text/javascript">
    (function () {
        var options = {
            whatsapp: "+39 ", // WhatsApp number
            call_to_action: "contacts", // Call to action
            position: "right", // Position may be 'right' or 'left'
        };
        var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
        var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
        s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
        var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
    })();
</script>

UPD:添加了Dmitry Bychenko的重要建议。

答案 1 :(得分:2)

DateTime值没有格式-只是一个值。 (就像int本身不是十进制或十六进制一样-您可以在将其转换为字符串时选择格式,默认使用十进制。)

您要传递给DateTime.ParseExact的字符串是预期的 input 格式-并且您的字符串的格式不是“ yyyy mm dd”。 (请注意,在日期/时间格式字符串中,“ mm”表示分钟,因此无论如何您都希望使用“ MM”而不是“ mm” ...但这在这里无济于事。)

您的日期格式为 nearly “ d MMM yyyy”(天,短月份的名称,年份),使用英语月份的名称-但问题是序数部分(“ st”,“ nd”, “ th”)。据我所知,没有DateTime.ParseExact处理此问题的简单方法。相反,我可能会使用正则表达式或简单的字符串替换来删除序数部分,以便您 do 拥有格式为“ d MMM yyyy”的字符串,然后对其进行解析。

对于字符串替换部分,对this question的答案是合适的。因此,这是一个使用示例数据的完整示例:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        Console.WriteLine(ParseWithOrdinals("10th Mar 2015"));
        Console.WriteLine(ParseWithOrdinals("1st Oct 2018"));
    }

    private static DateTime ParseWithOrdinals(string input) =>
        DateTime.ParseExact(
            RemoveOrdinals(input), // Text to parse
            "d MMM yyyy",          // Format of text
            CultureInfo.InvariantCulture); // Expect English month names, Gregorian calendar


    // From https://stackoverflow.com/questions/17710561
    private static string RemoveOrdinals(string input) =>
        input
            .Replace("0th", "0")
            .Replace("1st", "1")
            .Replace("2nd", "2")
            .Replace("3rd", "3")
            .Replace("11th", "11") // Need to handle these separately...
            .Replace("12th", "12")
            .Replace("13th", "13")
            .Replace("4th", "4")
            .Replace("5th", "5")
            .Replace("6th", "6")
            .Replace("7th", "7")
            .Replace("8th", "8")
            .Replace("9th", "9");
}

(请注意,我尚未在输出中将结果格式化为yyyy-MM-dd,因此您将获得本地日期/时间格式。)

答案 2 :(得分:1)

还有一种不带字符串删除/替换/正则表达式的本机方法

如果您知道这些字符,则可以在日期模式中使用'字符对它们进行转义。因此"15th Oct 2018"适用于这种模式"d'th' MMM yyyy"

现在有"st","nd","rd","th",因此您可以尝试其中的每一个并选择可以使用的。

TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)的重载中,您可以传递一系列允许的格式。

string input = "15th Oct 2018";
DateTime result = DateTime.Now;
string[] patterns = { "d'st' MMM yyyy", "d'nd' MMM yyyy", "d'rd' MMM yyyy", "d'th' MMM yyyy"};
bool success = DateTime.TryParseExact(input, patterns, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (success)
    Console.WriteLine(result.ToString("yyyy-MM-dd"));

https://dotnetfiddle.net/H8ulyo