Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a string type variable having date time value "19/05/18 06:20:40"
now i want to change this to only date like "19/05/18"

What I have tried:

tried this
Format(inDate, "dd/MM/yy")
but its not working for me
Posted
Updated 21-May-18 23:23pm

If you would like to display date in specific format, please read this:
Standard Date and Time Format Strings | Microsoft Docs[^]
Custom Numeric Format Strings | Microsoft Docs[^]

So, DateTime.ToString()[^] should do the job:
VB.NET
Dim stringdate = "19/05/18 06:20:40"
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Dim mydate = DateTime.ParseExact(stringdate, "dd/MM/yy HH:mm:ss", provider)
Dim formatdate = mydate.Tostring("dd/MM/yy")
'prints 19-05-18 in Poland
'prints 19.05.18 in Germany
'prints 19/05/18 in USA


As you can see a date format depends on system settings. In case when a date separator is different then "/", then you have to use DateTime.ToString Method (String, IFormatProvider) (System)[^]
VB.NET
Dim formatdate1 = mydate.Tostring("dd/MM/yy", New Globalization.CultureInfo("en-US"))
 
Share this answer
 
v2
Comments
Ralf Meier 24-May-18 4:59am    
This might be the best (much universal) way ... +5 from me !!!
Maciej Los 24-May-18 5:00am    
Thank you, Ralf.
When you have a String you should use String-Functions to handle it. In your case SubString could solve the Problem ...
VB
OutString = inDate.SubString(0,8)

The Format-Function will only work (like posted by you) if your Source-Variable has the Type of Date ...
 
Share this answer
 
Comments
Maciej Los 22-May-18 5:25am    
It does the job, but i'm not a follower of that method.
4.
Ralf Meier 24-May-18 4:58am    
Thanks for your vote ... :)
An alternative to Ralfs solution might be:
dim inDate as string = "19/05/18 06:20:40"
Console.WriteLine(inDate.Split(New Char() {" "c})(0))
This will work correctly too if the length of the date part varies.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900