Parse Date Time [Duplicate]

Parse Date Time [Duplicate]

Below is the Date Time format I am getting from an API.

Mon Apr 14 03:31:15 +0000 2014

How can I convert it to dd-MMM-yyyy HH:mm:ss Format.

I tried following code:

Dim strDate as String = "Mon Apr 14 03:31:15 +0000 2014"
Dim dateT as DateTime = DateTime.Parse(strDate)

I am getting following issue:

DateTime.Parse(strDate) {"String was not recognized as a valid DateTime."}

Any solution and suggestion is appreciated.

4

2 Answers

You can use DateTime.ParseExact like:

string str = "Mon Apr 14 03:31:15 +0000 2014";
DateTime dt = DateTime.ParseExact(str, 
                           "ddd MMM dd HH:mm:ss zzz yyyy", 
                           CultureInfo.InvariantCulture);

For more information see: Custom Date and Time Format Strings

For converting the parsed date to your required format do:

string formattedOutput = dt.ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

VB equivalent would be:

Dim dt As DateTime = DateTime.ParseExact(str,
                           "ddd MMM dd HH:mm:ss zzz yyyy",
                          System.Globalization.CultureInfo.InvariantCulture)
Dim formattedOutput As String = dt.ToString("dd-MMM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
2

string Date = (Convert.ToDateTime(control.Text)).ToString("dd/mm/yyyy")

string Date = (Convert.ToDateTime(control.Text)).ToShortDateString();

you may also research using a culture e.g

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="lab.aspx.cs" Inherits="lab"   MasterPageFile="~/Master.master"      Culture="en-CA" UICulture="en-CA" %>
1
Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.