简体   繁体   English

C#ToShortDateString

[英]C# ToShortDateString

I wrote this code in vb: 我在vb中编写了以下代码:

expireDate = (DateTime.Parse(decal.DecalExpireDate).ToShortDateString).ToString

Now I'm trying to write the same code in c#, this is what I came up with: 现在,我试图用c#编写相同的代码,这是我想出的:

expireDate = decal.DecalExpireDate.ToString();
expireDate = DateTime.Parse(expireDate).ToShortDateString();

Does anybody know how to simplify the c# code so it's one line and two. 有人知道如何简化c#代码,所以只有一行两行。 It's bugging me that I can do it in one line with vb, but not in c#. 我可以用vb在同一行中执行此操作,但在c#中却行不通。

decal.DecalExpireDate is a smallDateTime that I'm retrieving with linq. decal.DecalExpireDate是我正在使用linq检索的smallDateTime。 expireDate is a string that I'm returning in a function expireDate是我要在函数中返回的字符串

expireDate = DateTime.Parse(decal.DecalExpireDate.ToShortDateString()).ToString();

或者,更好的是

expireDate = decal.DecalExpireDate.Date.ToString();

在VB中几乎完全是这样:

    expireDate = DateTime.Parse(decal.DecalExpireDate.ToString()).ToShortDateString();

There is no need to call Parse here, because you are starting with a nullable DateTime (based on your comments). 无需在此处调用Parse,因为您从一个可为空的DateTime(根据您的评论)开始。 In fact, you'll get an error message if you try to parse your date when it's null. 实际上,如果您尝试在日期为null时解析日期,则会收到一条错误消息。

This will work as long as the decal expire date is not null: 只要贴花过期日期不为空,这将起作用:

var expireDate = decal.DecalExpireDate.Value.ToShortDateString();

To be safer, though, you should check for null first: 为了更加安全,您应该首先检查null:

var expireDate = decal.DecalExpireDate != null ? decal.DecalExpireDate.Value.ToShortDateString() : null;

You can read more about nullable types here: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx . 您可以在此处阅读有关可空类型的更多信息: http : //msdn.microsoft.com/zh-cn/library/2cf62fcy.aspx

var expireDate = DateTime.Parse(decal.DecalExpireDate).ToShortDateString;

SmallDateTime should already be returned as a DateTime format ( SQL-CLR Type Mapping (LINQ to SQL) ). SmallDateTime应该已经以DateTime格式返回( SQL-CLR类型映射(LINQ to SQL) )。

It should be as simple as: 它应该很简单:

expireDate = decal.DecalExpireDate.ToShortDateString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM