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

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Azeem112
  • 337
  • 1
  • 8
  • 23
  • 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 [mcve]. (Actually, it wouldn't even compile, as you're trying to parse `date` rather than `s`.) – Jon Skeet Oct 18 '17 at 08:34
  • 2
    That's still going to throw an exception. Please put the effort into providing a [mcve] which you've actually *run*. – Jon Skeet Oct 18 '17 at 08: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` https://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx – Timothy Groote Oct 18 '17 at 08:40
  • I created a DotNetFiddle for the Code and it doesn't even run: https://dotnetfiddle.net/baJVA3 – thmshd Oct 18 '17 at 08:41
  • Thanks a lot for pointing the error. but Its running fine in asp.net – Azeem112 Oct 18 '17 at 08:48
  • It isn't clear what you are asking, do you mean that you want the dt to hold the current time with a date specified in your date string? – Steve Ford Oct 18 '17 at 08:55
  • time issue is solved now. Its converting the string with current time. Why it's happening that I'm giving him a string in DD/MM/YYYY order and he giving me converted dt object in MM/DD/YYYY format. I want it to save in database in DMY order so when ever I get data from it i can get date in DMY order instead of MDY order – Azeem112 Oct 18 '17 at 09:08
  • @Azeem112 because you are using a *string*. A string is not a date. Just *don't* save a string. Use a date-typed field (ie date, datetime, datetime2), and use *parameterized queries* or an ORM to save a *Date*, not a string that contains something that could be interpreted as a date. Don't construct the query string by string concatenation either - appending a `DateTime` object to a string formats it using the current culture – Panagiotis Kanavos Oct 18 '17 at 09:39
  • @Azeem112 if you *have* to use a string, at least use a non-ambiguous format like `YYYYMMDD` or the full ISO8601 format. – Panagiotis Kanavos Oct 18 '17 at 09:42
  • @Azeem112 `In view I'm receiving dates in MM/DD/YYYY format`. No you aren't. You are receiving DateTime objects which have no order or formt. You are *displaying them as strings though* using the current locale's settings. If you don't want that, specify the format you want. Or change the view's culture. By default it's controlled by the *browser's* settings. – Panagiotis Kanavos Oct 18 '17 at 09:51
  • This *still* isn't a [mcve]. Can we copy/paste/compile/run? No. If all you're interested in is converting a string representation of a date into a `DateTime` value with the current local time, that's entirely reproducible in a console app. All your formatting queries are entirely separate. And I'd be utterly astonished if this code was really running without an exception in ASP.NET if the value of `date` is really just `23/12/2017`. – Jon Skeet Oct 18 '17 at 09:51

3 Answers3

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • 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 Oct 18 '17 at 09:29
  • @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 – Panagiotis Kanavos Oct 18 '17 at 09:33
  • @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? – Panagiotis Kanavos Oct 18 '17 at 09:35
  • 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 Oct 18 '17 at 09:42
  • @Azeem112 post the code in the *question*. And post all *relevant* code. Including the table schema and the classes. – Panagiotis Kanavos Oct 18 '17 at 09:46
  • @Azeem112 BTW why does the action accept a *string*? If the parameter is supposed to be a date, use `SaveDate(DateTime date)` and insist the client uses the correct format. ASP.NET MVC can parse date parameters just fine. Check this similar question https://stackoverflow.com/questions/1224201/how-do-i-pass-a-datetime-value-as-a-uri-parameter-in-asp-net-mvc – Panagiotis Kanavos Oct 18 '17 at 09:46
  • Because if i write datetime type as a parameter it will automatically convert it in MM/DD/YYYY order – Azeem112 Oct 18 '17 at 09:53
  • @Azeem112 so all those millions of developers that don't work in the US and *don't* have these issues are wrong? You just admitted that your *view* formats the dates without specifying a locale. I suspect you should be looking for an ASP.NET MVC tutorial, especially one covering internationalization and localization. The *only* case where you may get in trouble with `DateTime` is the Persian calendar. Everything else is a bug in the code – Panagiotis Kanavos Oct 18 '17 at 09:56
  • Thanks a lot for your help. I'll take MVC tutorials on localization and internationalization. – Azeem112 Oct 18 '17 at 10:02
4

This might works

 DateTime dt = DateTime.ParseExact(
            date,
            "dd/MM/yyyy",
            CultureInfo.InvariantCulture).Add(DateTime.Now.TimeOfDay);
        Console.WriteLine(dt);
duongthaiha
  • 855
  • 6
  • 17
  • 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) – Timothy Groote Oct 18 '17 at 08:43
  • @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". – Jon Skeet Oct 18 '17 at 08:44
  • Agree, without the context of what is he/she trying to do I cant guess – duongthaiha Oct 18 '17 at 08:45
  • Thanks for help. Its saving the current time but date is still in mm/dd/yyyy format. – Azeem112 Oct 18 '17 at 08:49
  • I'm just converting a date from input type date with current time to date time object. – Azeem112 Oct 18 '17 at 08:52
  • 1
    @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? – Panagiotis Kanavos Oct 18 '17 at 08:53
  • in US they use MDY date order but I'm trying to convert a date from an input [type=date] element to DMY order. I specified mu order in parse method "dd/MM/yyyy" its still ordering it as MDY and i don't know why – Azeem112 Oct 18 '17 at 09:00
  • @JonSkeet i still think it's not pretty to use the time form the *server* if the *client* could pass it along just as well (and risk running into trouble with the difference between the server's and the client's clock, or even time zone) (though admittely, using NodaTime could remedy the latter) – Timothy Groote Oct 18 '17 at 09:02
  • 1
    @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 – Panagiotis Kanavos Oct 18 '17 at 09:02
  • @PanagiotisKanavos yes dates are binary value but when i click on database column to explore the data in it, it's in MDY order. I want dates to store in DMY order so that whenever i get data from db i don't have to change MDY order to DMY everytime. – Azeem112 Oct 18 '17 at 09:11
  • 1
    @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 – Panagiotis Kanavos Oct 18 '17 at 09:16
  • @Azeem112 if the database field has a date type, just use whatever function is appropriate to get the month value. It will be 12 again. In SQL Server you'd write `MONTH(myDateField)` – Panagiotis Kanavos Oct 18 '17 at 09:17
  • @PanagiotisKanavos Time issue is solved. I have a database table name date having datetime field of 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 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 get value from my table I don't have to change order – Azeem112 Oct 18 '17 at 09:24
  • @Azeem112: "i want to save my date in it as DD/MM/YYYY so i don't need to change its order." If you pass the value as a `DateTime` value rather than as a string, the formatting is completely irrelevant. It's like deciding whether to store an integer in hex or in decimal - it's just irrelevant to the numeric value. – Jon Skeet Oct 18 '17 at 09:42
  • @JonSkeet Please can you share the method to show my date in my datetime object as DD/MM/YYYY order? asp.net use Razor and I didn't manage to find the code to this using Razor syntax – Azeem112 Oct 18 '17 at 09:50
  • @Azeem112: No, because that's **completely different** to the subject of this question. Each question should be self-contained, about *one* specific topic. – Jon Skeet Oct 18 '17 at 09:53
  • Thanks a lot for the help. My time issue is solved now. I'll ask a new question about ordering and viewing. – Azeem112 Oct 18 '17 at 10:00
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;
    }
Johan Herstad
  • 672
  • 7
  • 15
  • 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)](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/convert.cs#L1724) does. It's a call to `DateTime.Parse` with the CurrentCultureInfo passed explicitly – Panagiotis Kanavos Oct 18 '17 at 08:51
  • They return server time, my example return whatever time your contry is by specifying your local time code – Johan Herstad Oct 18 '17 at 08:52
  • That's just how I interpreted the question, because the other answers covered that and apparently he was not happy. – Johan Herstad Oct 18 '17 at 09:03
  • 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 – Panagiotis Kanavos Oct 18 '17 at 09:04
  • 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). – Johan Herstad Oct 18 '17 at 10:12