Dim
shouldBeDate =
"05/18/2019"
dateResult
As
Date
=
CDate
(shouldBeDate)
Console.WriteLine(dateResult)
"18/05/2019"
.ParseExact(shouldBeDate,
"dd/MM/yyyy"
, CultureInfo.InvariantCulture)
Imports
System.Globalization
Namespace
LanguageExtensions
Public
Module
DateTimeExtensions
''' <summary>
''' Convert string to date time using various formats
''' </summary>
''' <param name="sender"></param>
''' <returns></returns>
<Runtime.CompilerServices.Extension>
Function
ToDate(sender
String
)
format() = {
,
"d/M/yyyy"
"dd-MM-yyyy"
"MM/dd/yyyy"
}
dateValue
.TryParseExact(sender, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, dateValue)
Return
End
Console.WriteLine(
.ToDate)
dateFromLineInFile as
.ToDate
englishUS
New
CultureInfo(
"en-US"
dateTimeString
"20190518"
resultingDate
If
.TryParseExact(dateTimeString,
"yyyyMMdd"
, englishUS, DateTimeStyles.None, resultingDate)
Then
Console.WriteLine(resultingDate)
"201905180945"
"yyyyMMddhhmm"
CultureList()
Globalization.CultureInfo()
(
From T
In
Globalization.CultureInfo.GetCultures(Globalization.CultureTypes.SpecificCultures)
Order By T.EnglishName).ToArray
My
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Partial
Friend
Class
_Culture
''' Date separator for current culture
DateSeparator()
CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator
''' Return the Time Separator for current culture
''' <remarks></remarks>
TimeSeparator()
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator
CultureInfo()
CultureInfo.GetCultures(CultureTypes.SpecificCultures)
<HideModuleName()>
Custom_Culture
Private
ReadOnly
Instance
ThreadSafeObjectProvider(Of _Culture)
Property
Culture()
Get
Instance.GetInstance()
EnglishUK =
My.Culture.CultureList().FirstOrDefault(
(cultureInfo) cultureInfo.DisplayName =
"English (United Kingdom)"
).Name)
theDate
, EnglishUK, DateTimeStyles.None, theDate)
Console.WriteLine(theDate)
Console.WriteLine(IsDate(
"5/18/2019"
)))
Console.WriteLine(IsDate(#05/18/2019#))
"May 18, 2019"
))
dateStringValue =
.TryParse(dateStringValue, dateValue)
Console.WriteLine(dateValue)
dictValues
Dictionary(Of
, CultureInfo) From {
{
"12 Mai 2019"
"de-DE"
)},
"12 May 2019"
"12 mayo 2019"
"es-MX"
)}
For
Each
kvp
dateResultValue
.Parse(kvp.Key, kvp.Value)
Next
''' Responsible for formatting the date as a long date if
''' the value is a valid date.
''' <param name="e"></param>
Sub
BindingFormatting(sender
Object
, e
ConvertEventArgs)
Not
.TryParse(e.Value.ToString(),
Nothing
' we have a value that can not represent a date
Exit
e.Value =
(e.Value).ToLongDateString
''' Since a Date control is not being used this event will
''' determine if a valid Date has been entered, if the string
''' entered can not represent a date reset the value.
BindingParser(sender
MessageBox.Show(
"Sorry but you entered a invalid date, resetting date."
person = dataOperations.LoadData().
FirstOrDefault(
(p) p.Id =
CType
(bsPeople.Current, Person).Id)
person IsNot
e.Value = person.BirthDate
DataGridView1_CellFormatting(sender
DataGridViewCellFormattingEventArgs) _
Handles
DataGridView1.CellFormatting
e.ColumnIndex = BirthDateColumnIndex
d
.TryParse(e.Value.ToString, d)
e.Value = d.ToString(
"MM-dd-yyyy"
e.FormattingApplied =
True
BindingData.Classes
''' Demonstrates Date formatting with Binding class
Form1
bsPeople
BindingSource
dataOperations
DataOperations
birthDateColumnIndex
Integer
= 0
Form1_Load(sender
EventArgs)
MyBase
.Load
' load mocked data
bsPeople =
With
.DataSource = dataOperations.LoadData
BindingNavigator1.BindingSource = bsPeople
DataGridView1.DataSource = bsPeople
firstNameTextbox.DataBindings.Add(
"Text"
, bsPeople,
"FirstName"
lastNameTextBox.DataBindings.Add(
"LastName"
SetupBirthDateBinding()
' Provides the column index to use in CellFormatting event
birthDateColumnIndex = DataGridView1.Columns(
"BirthDate"
).Index
firstNameTextbox.SelectionStart = firstNameTextbox.Text.Length
''' Called from Form Load event to create a Binding object for
''' controlling how the BirthDate property is presented to the
''' user interface. This code could had been in form load, the reason
''' for separating this code from form load is to push focus to this
''' code.
binding
Binding =
Binding(
AddHandler
binding.Parse,
AddressOf
BindingParser
binding.Format,
BindingFormatting
birthdayTextBox.DataBindings.Add(binding)
e.ColumnIndex = birthDateColumnIndex
SELECT
FORMAT(GETDATE(),
'd'
'en-us'
AS
English ,
'de-DE'
German ,
'es-MX'
Spanish;
SET
LANGUAGE british;
LanguageID = langid ,
name
alias ,
dateformat
FROM
sys.syslanguages
ORDER
BY
langid;
Classes
TimeSpanItem
Id()
TimeSpan()
TimeSpan
Overrides
ToString()
$
"{TimeSpan}"
NameSpace
System.Data.SqlClient
TimeDataOperations
Inherits
SqlServerConnection
()
' Change this to your server name or .\SQLEXPRESS
DatabaseServer =
"KARENS-PC"
DefaultCatalog =
"DateTimeDatabase"
ReadHours()
List(Of TimeSpanItem)
timeList
selectStatement
"SELECT id,TimeValue FROM dbo.HoursTable"
Using cn
SqlConnection
{.ConnectionString = ConnectionString}
Using cmd
SqlCommand
{.Connection = cn}
cmd.CommandText = selectStatement
cn.Open()
reader = cmd.ExecuteReader()
While
reader.Read()
timeList.Add(
TimeSpanItem()
.Id = reader.GetInt32(0),
.TimeSpan = reader.GetTimeSpan(1)
})
Using
BaseLibrary.Classes
EventArgs) _
timeOperations
ListBox1.DataSource = timeOperations.ReadHours()
TestClasses
TestBase
Protected
ImperfectStringArrayForConvertingToTimeSpan()
"0"
"14"
"1:2:3"
"0:0:0.250"
"10.20:30:40.50"
"99.23:59:59.9999999"
"0023:0059:0059.0099"
"23:0:0"
"24:0:0"
"0:59:0"
"0:60:0"
"0:0:59"
"0:0:60"
"10:"
"10:0"
":10"
"0:10"
"10:20:"
"10:20:0"
".123"
"0.12:00"
"10."
"10.12"
"10.12:00"
CanConvertToIntArray(sender()
Boolean
testValue
sender.All(
(input)
.TryParse(input, testValue))
CanConvertToTimeSpanArray(sender()
(input) TimeSpan.TryParse(input, testValue))
<TestMethod()>
ValidateNotAllStringElementsCanBeConvertToTimeSpanTest()
Assert.IsFalse(ImperfectStringArrayForConvertingToTimeSpan.CanConvertToTimeSpanArray())
ToTimeSpanPreserveArray(sender()
Array.ConvertAll(sender,
value
TimeSpan.TryParse(input, value)
ToTimeSpanArray(sender()
.IsTimeSpan = TimeSpan.TryParse(input, value),
.Value = value
).
Where(
(result) result.IsTimeSpan).
Select
(result) result.Value).
ToArray()
PreserveTimeSpanArrayElementsTest()
test = ImperfectStringArrayForConvertingToTimeSpan.ToTimeSpanPreserveArray()
Assert.IsTrue(test.Length = 24)
Console.WriteLine(test.TimeSpanArrayToString)
''' Demonstrates how an expected conversion may fail because
''' the assumption is incorrect for the expected result in the
''' first assertion while the second assertion is correct.
SimpleConversionFromStringToDateTest()
dateValueGerman =
"05.11.2019"
dateValueUS =
"05/11/2019"
'
' Parse will convert to current culture
resultDate
.Parse(dateValueGerman)
test1 = resultDate.ToString(
' date string will not match as result1 has / as date separator
Assert.IsFalse(test1 = dateValueGerman)
' This time both values match as the right date separator is there.
Assert.IsTrue(test1 = dateValueUs)
''' Given a string array in another culture convert to current culture
''' using the date format for the dates in the string array, if the format
''' is not correct ParseExact will throw an exception so the developer needs
''' to know what the culture is, in this case in the string array.
ConvertingStringFromOneCultureToAnotherAsDateTest()
dateFormat =
"MM.dd.yyyy"
stringDateArray =
"05.01.2019"
"05.02.2019"
"05.03.2019"
"05.04.2019"
"05.05.2019"
"05.06.2019"
"05.07.2019"
"05.08.2019"
"05.09.2019"
"05.10.2019"
expectedResults =
#05/01/2019#, #05/02/2019#, #05/03/2019#, #05/04/2019#,
#05/05/2019#, #05/06/2019#, #05/07/2019#, #05/08/2019#,
#05/09/2019#, #05/10/2019#
resultDateArray(9)
index
To
stringDateArray.Length - 1
resultDateArray(index) =
.ParseExact(stringDateArray(index), dateFormat,
Assert.IsTrue(resultDateArray.SequenceEqual(expectedResults))