Is there any way I can convert a date of format: dd/mm/yyyy to yyyymmdd format? For example from : 25/07/2011 to 20110725? in VB.NET?
Convert mm/dd/yyyy to yyyymmdd (VB.NET)
Asked Answered
Dates themselves don't have formats inherently. You can parse a string into a DateTime
by parsing it with dd/MM/yyyy
format and then convert that into a string using yyyyMMdd
format:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
string reformatted = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
Or in VB:
Dim date as DateTime = DateTime.ParseExact(text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Dim reformatted as String = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture)
(And make sure you have an import for System.Globalization
.)
However, ideally you should keep it as a DateTime
(or similar) for as long as possible.
@reggie: For the second line? He could, but it would be more work IMO. Why specify a compound string format specifier when you only want to format a single value? –
Oldest
Thanks for the tip, the second line is what I missed! –
Briony
I'm not at all accomplished in vb.net, so please don't take this as a criticism because it is just a question..could be something I'm missing. I understand a little bit about what the whole Culture piece refers to from a semantic standpoint, but from a syntactical standpoint it appears to be completely ... Not accepted, when I try to type it into the SSIS IDE for .net. What am I missing? –
Elyot
@Isaac: I don't know anything about the SSIS IDE, but the original answer was only in C#, not VB. I've provided a VB version as well now. Make sure you've imported the
System.Globalization
namespace. –
Oldest CDate(Datetext).ToString("yyyyMMdd")
This answer could fail depending on the culture. That's why Jon's answer is better than this one. For example, how would decide if 10/12/2017 is 10th December or 12th October without the ParseExact? –
Farinaceous
Use the DateTime.ParseExact
method to parse the date, then use DateTimeObj.ToString("yyyyMMdd")
.
Public Function DateFormateYYYYMMDD(ByVal Dtp As DateTimePicker) As String
Try
Dim StrDate, StrYear, StrMonth, StrDay As String
StrDate = FormatDateTime(Dtp.Value, DateFormat.ShortDate)
StrMonth = Month(Dtp.Value)
StrDay = Convert.ToString(Dtp.Value.Day)
StrYear = Year(Dtp.Value)
StrDate = StrYear + "-" + StrMonth + "-" + StrDay
Return StrDate
Catch ex As Exception
End Try
End Function
this function can be used to convert datetime picker value format to yyyyMMdd
© 2022 - 2024 — McMap. All rights reserved.
String.Format
method? – Prober