VB.NET 从日期开始只获取年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5560019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:24:51  来源:igfitidea点击:

VB.NET Get Only Year from Date

vb.netdatetimedatecasting

提问by Dave Mackey

I'm pulling into a variable a datetime value. Now, I want to post this value back to my database, but I need it to be only the year digits. How do I get VB.NET to trim the month, day, and time off and just return the four character year (e.g. 2011)?

我正在拉入一个变量日期时间值。现在,我想将此值发布回我的数据库,但我只需要它是年份数字。如何让 VB.NET 修剪月、日和时间并只返回四个字符的年份(例如 2011)?

回答by ScottE

Date.Today.Yearis what you're looking for, or for an existing date, just someDateVariable.Year

Date.Today.Year是您正在寻找的,或现有的日期,只是 someDateVariable.Year

回答by Brandon Montgomery

Dim myDate As DateTime = #1/1/2011#
Dim myYear As Int32 = myDate.Year

回答by Rich S

There is a property on the DateTime structure called 'Year'. This returns an integer representing just the year.

DateTime 结构上有一个名为“Year”的属性。这将返回一个仅代表年份的整数。

If you need to convert this to a string, just use the ToString() function.

如果您需要将其转换为字符串,只需使用 ToString() 函数。

So..

所以..

MyDT.Year.ToString()

That's a c# example, I'm sure VB.Net is going to be very similar.

这是 ac# 示例,我确信 VB.Net 将非常相似。

回答by jude.MMMM

i know this is a bit late to answer but, it wont hurt telling, try "year(now) " and load it to a variable Example:

我知道回答有点晚了,但是,说出来不会有什么坏处,请尝试“year(now)”并将其加载到变量中 示例:

Dim Year_in_Digits = Year(Now)

回答by Insub

I just had to do this for my VB program.

我只需要为我的 VB 程序执行此操作。

 Dim Year As Integer    
 Year = Convert.ToInt32(Now.ToString("yyyy"))

Use just "yy"if you want two digit year. Then, when you need to display it somewhere:

只使用"yy"如果你希望两个数字的年份。然后,当您需要在某处显示它时:

year.tostring

回答by james ace

I know it's late,but am sure i will help someone

我知道已经晚了,但我相信我会帮助某人

To get exact year in vb:

要在vb 中获得确切的年份:

Dim date As String=Now.Year.ToString()

Dim date As String=Now.Year.ToString()

回答by Humphrey

I hope this will help because I tested it

我希望这会有所帮助,因为我测试了它

Dim nowYear As Integer = Date.Now.Year