1
string date = "23/12/2017";

DateTime dt = DateTime.ParseExact(
  date, 
 "dd/MM/yyyy hh:mm:ss tt", 
  CultureInfo.InvariantCulture);

but in dt it's giving me 12/23/2017 12:00:00 AM

what approach do I have to use to convert this string to dd/mm/yyyy with current time, as if i run this code at 03:20 PM i want "23/12/2017 03:20:00 PM" in my dt object

I have an ASP.NET MVC action that accepts a date as a string and saves it to a a database table, in a field whose type is DATE.

I'm saving my dt object in it. i want to save my date in it as DD/MM/YYYY so i don't need to change its order. Right now dt object is in MM/DD/YYYY format. so when i explore my table data, it shows me data(dates) in MM/DD/YYYY order. i want to order my dt object as DD/MM/YYYY to it saves in table as DD/MM/YYYY so whenever I get value from my table I don't have to change order

/// asp.net Entities link to create connection with DataBase
    private DatabaseEntities db = new DatabaseEntities(); 

//// Method to Save date in database
    public ActionResult SaveDate(string date){
        var DateTableObject = new Date();
        DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Add(DateTime.Now.TimeOfDay); 

       DateTableObject.Date = dt;
       db.Date.add(DateTableObject);
       db.SaveChanges();
    }

    //// Model class
    public class Date{
       public DateTime Date {set; get;}
    }

/// Method to get dates
 public ActionResult GetDates(){
   return View(db.Date.tolist());
}

In view I'm receiving dates in MM/DD/YYYY format

11
  • 2
    Do you mean "23/12/2017 03:20:00 PM"? If not, why would you lose the 20 minutes? Which time zone do you want to use for the time - the system time zone, UTC, or something else? (Note that this really has nothing to do with ASP.NET.) I would expect your current code to throw an exception, given that you're not giving the format that you're claiming. Please provide a minimal reproducible example. (Actually, it wouldn't even compile, as you're trying to parse date rather than s.) Commented Oct 18, 2017 at 8:34
  • 2
    That's still going to throw an exception. Please put the effort into providing a minimal reproducible example which you've actually run. Commented Oct 18, 2017 at 8:40
  • since you are parsing a datetime without time, you should get the result you are seeing. you could add the current time of day if you wanted to by just adding DateTime.TimeOfDay msdn.microsoft.com/en-us/library/… Commented Oct 18, 2017 at 8:40
  • I created a DotNetFiddle for the Code and it doesn't even run: dotnetfiddle.net/baJVA3 Commented Oct 18, 2017 at 8:41
  • Thanks a lot for pointing the error. but Its running fine in asp.net Commented Oct 18, 2017 at 8:48

3 Answers 3

5

If you know the correct culture for the date string, you can use DateTime.Parse to parse the date and then add the current local time :

var finalDateTime = DateTime.Parse("23/12/2017",CultureInfo.GetCultureInfo("en-GB"))
                            .Add(DateTime.Now.TimeOfDay);

Many countries use the dd/MM/YYYY format, so you can use one as a fallback even if you don't know the actual locale.

If you don't know the locale, only the format, you can use ParseExact to parse the date only :

var finalDateTime = DateTime.ParseExact("23/12/2017","dd/MM/yyyy", CultureInfo.InvariantCulture)
                            .Add(DateTime.Now.TimeOfDay);

The returned value is a date whose value is December 23, 2017 and the current time.

Don't be confused by the debugger's display. Dates have no format, they are binary values. The debugger has to display the value in some way though. If, as many developers do, you use a US locale, you'll see the date as MM/dd/YYYY. If you check the Month property though, it will be 12.

Sign up to request clarification or add additional context in comments.

9 Comments

but the debugger is saving the date as MM/DD/YYYY format in database too. I want to change it to DD/MM/YYYY so i can save it in DD/MM/YYYY order and don't have to change the order exclusively.
@Azeem112 the debugger doesn't save anything. Your code does. The debugger displays values as tooltips and watch variables. Post your code if you have an issue. BTW insisting there is some sort of format in dates is pointless. I'm working in a non-US locale too. Millions of devs do, for decades. Those that have problems either stored strings instead of dates, or were confused by a formatted value. Anyway, post your code
@Azeem112 actually, my dev machine uses a Greek locale so I can write DateTime.Parse("23/12/2017") directly and get a date in December. My SQL Server has a US locale, and I don't get any issues at all. Are you storing the values using "dynamic sql" instead of parameterized queries perhaps?
private DatabaseEntities db = new DatabaseEntities(); public void SaveDate(string date){ var DateTableObject = new Date(); DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Add(DateTime.Now.TimeOfDay); DateTableObject.Date = dt; db.Date.add(DateTableObject); db.SaveChanges(); } public class Date{ public DateTime Date {set; get;} }
@Azeem112 post the code in the question. And post all relevant code. Including the table schema and the classes.
|
4

This might works

 DateTime dt = DateTime.ParseExact(
            date,
            "dd/MM/yyyy",
            CultureInfo.InvariantCulture).Add(DateTime.Now.TimeOfDay);
        Console.WriteLine(dt);

17 Comments

while this would do what OP seems to want, it's still odd that OP wants to add the current time to the parsed date (the only reason you would want to parse a date if it is not guaranteed to be the current date)
@TimothyGroote: That's not particularly strange. For example, suppose you were writing a calendaring app, and you're creating a new event. The user might first choose the date, then you default the date/time to "the current time of day on the specified date".
@Azeem112 dates have no format. Are you confusing the debugger's display for the actual value? Or did you try to format the date into a string without specifying a non-US locale? Are you using a US locale like most developers perhaps?
@Azeem112 again, dates have NO FORMAT. They are binary values. If you don't believe me, or the docs, check the .Month property. It's 12. Formats come into play only when you convert the binary value into a string. A watch variable has to convert the date into a string for display. If you expand it though, you'll see that Month is 12. Console.WriteLine also has to convert the value into a string
@Azeem112 what database? You never mentioned a database. Nothing changes though. Either you have a bug and store dates into string columns, or you confuse how SSMS or whatever client tool you use displays the columns. If you store dates as strings, don't. Change the type to an actual date. If you can't, you'll have to control how the dates are converted to strings by specifying the format when you save to the database
|
0

Here's just some simple example I use to convert strings to datetime and to get datetime by timezone. The question is a bit unclear so this might add to a solution.

string date;
DateTime dt = Convert.ToDateTime(date);

to string:

dt.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture);

get currentTime in local language:

public static DateTime GetCurrentTime()
    {
        TimeZoneInfo timeZone;
        DateTime time;
        try
        {
            timeZone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
            time = TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone);
        }
        catch (Exception)
        {
            try
            {
                timeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
                time = TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone);
            }
            catch (Exception)
            {
                //logg not succeed
                time = DateTime.Now;
            }

        }
        return time;
    }

5 Comments

Why do any of this? DateTime has .Now and .UtNow properties that return the current time. You can extract the time portion with TimeOfDay. Besides, why do you assume that the string is in the user's locale? That what Convert.ToDateTime(dates) does. It's a call to DateTime.Parse with the CurrentCultureInfo passed explicitly
They return server time, my example return whatever time your contry is by specifying your local time code
That's just how I interpreted the question, because the other answers covered that and apparently he was not happy.
Noone asked about timezone conversion. The OP's format doesn't contain dashes either. Nothing in this answer parses dates, which is quite clear in the question
As I interpret the question: i'ts very normal to use strings for dates in the frontend. So If he wants to populate that string to show some date in a local format, he must convert a datetime to display it in his string. So he could use string date = GetCurrentTime(). Now if he gets that string back from the frontend, it is easy to convert to datetime again and then store it in database with the correct format: DateTime dt = Convert.ToDateTime(date); This will completely solve his problem as i interpret it(he can change the locale and format values to his liking).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.