user1468537
user1468537

Reputation: 703

asp.net DateTime manipulation

I have various strings of type: 7/12/2012 12:02:39 AM and would like to convert them all to just 7/12/2012 12:00:00 AM Basically the date needs be the same, just the time must be set to 12:00:00 AM for all.

What is the best way to approach that? Except just looking for " " and replacing with 12:00:00 AM

Upvotes: 0

Views: 267

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

First, parse them to a DateTime. Then you can use the Date property(0h) and parse it back to a String by using DateTime.ToString:

var oldDate = DateTime.Parse("7/12/2012 12:02:39 AM");
var usCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
var newDateStr = oldDate.Date.ToString( usCulture );

Custom Date and Time Format Strings

only just noticed that 12 AM is midnight not highnoon

You can create new DateTime instance via constuctor:

var newDate = new DateTime(oldDate.Year, oldDate.Month, oldDate.Day, 12, 0, 0); 

or by adding 12 hours to the date part of the DateTime(0h):

var newDate = oldDate.Date.AddHours(12);

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

  1. Parse them as DateTime
  2. Write them back to string using yourDateTime.Date.ToString(@"G", CultureInfo.CreateSpecificCulture("en-us"))

Upvotes: 1

Amir Ismail
Amir Ismail

Reputation: 3883

use DateTime.Parse and specify the CulterInfo

DateTime mydat = DateTime.Parse(myString, CultureInfo.InvariantCulture);

Upvotes: 0

Related Questions