如何在DateTime变量中更改给定日期的格式?

时间:2017-12-11 21:34:12

标签: c# asp.net datetime

我之前已经问过类似的问题,但我无法找到符合我要求的合适解决方案。

我通过QueryString传递日期并在目的地将其读取为:

string fromDateQS = Request.QueryString["FromDate"];

我以mm/dd/yyyy格式获取输出。鉴于,我要求日期采用mm-dd-yyyy格式。如何更改格式?

4 个答案:

答案 0 :(得分:1)

这个exaple向您展示了两种方法将Dateinputstring转换为符合您需求的输出。您可以使用任一静态函数,并为其提供Request.QueryString["FromDate"]作为输入 - 如果这是一个字符串。

using System;
using System.Linq;
using System.Globalization;

public class Program
{
    // **Solution 1:** 
    // Take your string, parse it into DateTime, print is as you like:
    public static string DateParser(string d)
    {
        string[] possibleFormats = new[]{"MM/dd/yyyy", "MM/d/yyyy",
                                         "M/dd/yyyy", "M/d/yyyy"};

        DateTime parsedDate;

        // try each possible format
        foreach (var format in possibleFormats)
        {
            if (DateTime.TryParseExact(d, format, 
                System.Globalization.CultureInfo.InvariantCulture, 
                DateTimeStyles.None, out parsedDate))
            {
                return parsedDate.ToString("MM-dd-yyyy");
            }
        }
        // this will happen if the input is malformed
        return null;
    }

    // **Solution 2:**  
    // for your special case this will simply replace the `/` by `-`  
    // all the numbers are already in the correct locations...      
    public static string DateStringFixer(string d) {return d.Replace('/','-'); }

以下代码仅用于测试输出,以便您可以验证它是否有效。在控制台项目中使用它 - 它生成大约370/11个DateTimes,将它们格式化为4种方式并使用两个函数输出它们。

它还在末尾输出一片垃圾DateTime-String。

    public static void Test()
    {
      var dt = new DateTime (2017, 1, 1);

      // create testdates throughout the year, 11 days apart
      var dates = Enumerable.Range (0, 370).Where (r => r % 11 == 0)
                  .ToList ().Select (delta => dt.AddDays (delta));

      string dStr;
      string dStrAligned;
      foreach(var d in dates)
      {
          dStr = d.ToString("MM/dd/yyyy");
          dStrAligned = (dStr+"   ").Substring(0,10);
          Console.WriteLine(dStrAligned + "\tby Parsing: '" +  DateParser(dStr) + 
              "'\tby replace: '" + DateStringFixer(dStr));

          dStr = d.ToString("MM/d/yyyy");
          dStrAligned = (dStr+"   ").Substring(0,10);
          Console.WriteLine(dStrAligned + "\tby Parsing: '" + DateParser(dStr) +
              "'\tby replace: '" + DateStringFixer(dStr));

          dStr = d.ToString("M/dd/yyyy");
          dStrAligned = (dStr+"   ").Substring(0,10);
          Console.WriteLine(dStrAligned + "\tby Parsing: '" + DateParser(dStr) + 
              "'\tby replace: '" + DateStringFixer(dStr));

          dStr = d.ToString("M/d/yyyy");
          dStrAligned = (dStr+"   ").Substring(0,10);
          Console.WriteLine(dStrAligned + "\tby Parsing: '" + DateParser(dStr) + 
              "'\tby replace: '" + DateStringFixer(dStr) + "\n");

      }      
          Console.WriteLine("Malformed input:");

          var dStr2 = "24/7/365 service";
          Console.WriteLine(dStr2 + "\tby Parsing: '" + DateParser(dStr2) +
              "'\tby replace: '" + DateStringFixer(dStr2));
    }

    public static void Main() { Test(); }
}

输出:

01/01/2017    by Parsing: '01-01-2017'    by replace: '01-01-2017
01/1/2017     by Parsing: '01-01-2017'    by replace: '01-1-2017
1/01/2017     by Parsing: '01-01-2017'    by replace: '1-01-2017
1/1/2017      by Parsing: '01-01-2017'    by replace: '1-1-2017

01/12/2017    by Parsing: '01-12-2017'    by replace: '01-12-2017
01/12/2017    by Parsing: '01-12-2017'    by replace: '01-12-2017
1/12/2017     by Parsing: '01-12-2017'    by replace: '1-12-2017
1/12/2017     by Parsing: '01-12-2017'    by replace: '1-12-2017

== removed lots of similar output ==

12/30/2017    by Parsing: '12-30-2017'    by replace: '12-30-2017
12/30/2017    by Parsing: '12-30-2017'    by replace: '12-30-2017
12/30/2017    by Parsing: '12-30-2017'    by replace: '12-30-2017
12/30/2017    by Parsing: '12-30-2017'    by replace: '12-30-2017

Malformed input:
24/7/365 service    by Parsing: ''    by replace: '24-7-365 service

答案 1 :(得分:1)

String date = DateTime.ParseExact(Request.QueryString["FromDate"], "MM/dd/yyyy", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");

答案 2 :(得分:1)

首先,您必须将您从查询字符串接收的日期转换为G = nx.DiGraph() G.add_nodes_from(['A', 'B', 'C', 'D']) G.add_edges_from([('A', 'B'), ('B', 'C'), ('B', 'D')]) type = 'layer' for node in G.nodes(): if node in ('A', 'B'): G.node[node][type] = '1' else: G.node[node][type] = '2' d = json_graph.node_link_data(G) 对象

DateTime

在此之后,您可以从string fromDateQS = Request.QueryString["FromDate"]; DateTime dt = DateTime.ParseExact(fromDateQS, "mm/dd/yyyy", null); 对象获得所需格式的日期。

dt

string formattedDate = dt.ToString("mm-dd-yyyy");

答案 3 :(得分:1)

DateTime在这里工作正常,它将一个字符串作为参数,如果它可以解析它,它会将它输出到您作为第二个参数传递的string fromDateQS = Request.QueryString["FromDate"]; DateTime dt = new DateTime(); if (DateTime.TryParse(fromDateQS, out dt)) { System.Diagnostics.Debug.WriteLine(dt.ToString("MM-dd-yyyy")); } 对象。请参阅here

TryParse

我更喜欢ParseExact而不是ParseExact,因为如果无法解析字符串,则column会抛出异常。