1

I want to know how to convert string that my contains for example the string maybe (1/1/2015) or (14/1/2015) or (14/11/2015) and convert to a date

string mydate;
DateTime dt = DateTime.ParseExact(mydate, "dd/MM/yyyy", CultureInfo.InvariantCulture); 

Is this right way?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Saleh923
  • 105
  • 8
  • 5
    which language? java or C#? – Bacteria Nov 25 '15 at 11:20
  • Possible duplicate of [Converting dd/mm/yyyy formatted string to Datetime](http://stackoverflow.com/questions/15738608/converting-dd-mm-yyyy-formatted-string-to-datetime) – Kannan Thangadurai Nov 25 '15 at 11:20
  • 2
    Possible duplicate of [Converting a String to DateTime](http://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Viraj Nalawade Nov 25 '15 at 11:21
  • I am using C# I know there is other Posts to convert string to Datetime but they are talking about converting string like (dd/mm/yyyy) is it the same for string contains string like (d/m/yyyy) like (1/1/2015) – Saleh923 Nov 25 '15 at 11:30
  • Hi @Saleh923, The main difference between "d/m/yyyy" & "dd/mm/yyyy" is month/day numbers without/with leading zeroes – Rajeesh Menoth Nov 25 '15 at 11:42

4 Answers4

3

Since neither your days nor months have a leading zero for single digits, you need to use d/M/yyyy format instead.

string mydate;
DateTime dt = DateTime.ParseExact(mydate, "d/M/yyyy", CultureInfo.InvariantCulture); 

This will successfully parse all three kind strings that you have.

Further reading:

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Try this,

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
Date date = null;

try
{
    date = df.parse(listData.get(position).get("datetime"));
    strDateTime = outputformat.format(date);
}
catch (Exception e)
{
    e.printStackTrace();
}

If you need the output like this --> 1/1/2015

just change the formatted method d/m/yyyy

 DateFormat outputformat = new SimpleDateFormat("d/m/yyyy");

All the date format, visit this link:

http://developer.android.com/reference/java/text/SimpleDateFormat.html

Parth Bhayani
  • 1,894
  • 3
  • 17
  • 35
0

In java you can try the below code :-

 String str_date="14/1/2015";
 DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
 Date date = formatter.parse(str_date);

Here's an link of relevance from the javadoc, listing all available format patterns:

Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
0

You can easily use SimpleDateFormat for parsing between Date and String.

String strDate = "2013-05-15T10:00:00-0700";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date date = dateFormat.parse(strDate);
System.out.println(date);