如何比较DateTime值

时间:2014-08-13 16:41:54

标签: c# string datetime windows-phone-8

我将应用的第一个发布日期加上三天后保存为字符串值。然后我尝试在MainPage为NavigatedTo时执行字符串比较以比较这些字符串值。需要注意的是,这必须适用于任何文化集,尽管我从此处理解http://msdn.microsoft.com/en-us/library/system.datetime.now(v=vs.110).aspx DateTime.Now将始终获取本地值以进行正确比较。目前,我在执行此操作时收到TargetInvocationException,并且不确定如何解决问题

首次将应用程序启动到自定义Settings类时将其存储,这将保存字符串值

Settings.FutureDate.Value = DateTime.Now.AddDays(3).ToString();

加载后在应用页面中查看此内容

DateTime currentDate = DateTime.Now;
DateTime futureDate = DateTime.Parse(Settings.FutueDate.Value); 

//If three days has passed, notify user
if (currentDate >= DateTime.Parse(Settings.FutureDate.Value)) //TargetInvocationException error occurs here
{
    MessageBox.Show("Three days has passed.");
}

修改

在比较之前检查上面的currentDateSettings.FutureDate.Value值时,我会看到以下内容。

currentDate = {8/13/2014 3:07:17 PM}
futureDate = {8/16/2014 3:07:09 PM}

1 个答案:

答案 0 :(得分:2)

我认为您应该将日期本身存储为DateTime,而不是使用字符串,如果Settings.FutureDateNullable<DateTime>那么:

Settings.FutureDate= DateTime.Now.AddDays(3);

然后您的代码变为:

DateTime currentDate = DateTime.Now;

if (Settings.FutureDate)
{
    //If three days has passed, notify user
    if (currentDate >= Settings.FutureDate.Value) 
    {
        MessageBox.Show("Three days has passed.");
    }
}

没有理由存储字符串而不是DateTime本身,因为您可以随时方便地获取字符串。如果是因为DateTime创建了string,则很可能会消除您的错误。

请打印字符串FutureDate.Value的值吗?还尝试按以下方式拆分代码并告诉我们导致错误的行:

DateTime currentDate = DateTime.Now;

DateTime settingsDate = DateTime.Parse(Settings.FutureDate.Value);
if (currentDate >= settingsDate) 
{        //If three days has passed, notify user
    if (currentDate >= Settings.FutureDate.Value) 
    {
        MessageBox.Show("Three days has passed.");
    }
}

我怀疑错误会发生在DateTime.Parse上。要知道为什么我们需要您打印Settings.FutureDate.Value的值。

EDIT1: 我看到了你的字符串,你没有说出Settings.FutureDate的类型。但是,这对我来说是一个全新的项目,请注意ParseExact我提供要解析的字符串的确切格式。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class Settings
    {


        public static string FutureDate { get; set; }

    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Settings.FutureDate = "8/16/2014 3:07:09 PM";
        }



        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime futureDate = DateTime.ParseExact(Settings.FutureDate, "M/d/yyyy h:mm:ss tt", provider);

            if (currentDate >= futureDate) //TargetInvocationException error occurs here
            {
                MessageBox.Show("Three days has passed.");
            }
        }
    }
}