Not getting proper date time format in c# - c#

I'm unable get local time . im getting data like this from the api
sample data
2017-03-06T09:34:20.545Z
Desired Out put
3/6/2017, 3:04:20 PM
im getting value like this - 06/03/2017 04:34:20 AM
how to get the proper time in the format "3/6/2017, 3:04:20 PM".
i tried to localize the time but its giving incorrect date time.
data type
public string UpdatedTime { get; set; }
string updtime = bin.timestamp;//03/06/2017 12:51:33
binModel.UpdatedTime = Convert.ToDateTime(updtime).ToString("M/d/yyyy, h:mm:ss tt", CultureInfo.InvariantCulture);//expected time - 3/6/2017, 6:21:33 PM

You have incorrect format here:
"dd/MM/yyyy HH:mm:ss tt"
HH is used for 24 hours format, but you use AM/PM so you need 12 hours format. Use hh.
You sample data is:
2017-03-06T09:34:20.545Z
it means. year is 2017, month is 03, day is 06 and the same for time.
For desired output you need Month/Day/Year. But you use this format:
"dd/MM/yyyy HH:mm:ss tt"
here you get Day/Month/Year.
You should change your format to (also without zeros in front and with comma):
"M/d/yyyy, h:mm:ss tt"

Try this Code:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString("dd/MM/yyyy,hh:mm:ss tt"); // case sensitive
}

I personally always reference this page when I forget how to format timestamps. If you must use strings, and not DateTime, you can do this.
obj.UpdatedTime = string.Format("{0: d/m/yyyy, HH:mm:ss tt", Convert.ToDateTime(data)});
The format of the string can be whatever your choosing, but the page linked has always been the most helpful for me. If you can use a DateTime property, just do this. You will always want to wrap this in a try/catch and verify you're getting a value you want.
obj.UpdatedTime = Convert.ToDateTime(data);
Cheers

Related

ASP.NET format string date

I am connecting to a database, executing a query, and putting the data in a list. I have strings that have dates like so mm/dd/yyyy hour:minute:second AM or PM I am looking to format this data into yyyy-mm-dd with no time.
This is where I am assigning the data:
airportItems.ContractReceived_F = dataReader.GetValue(1).ToString();
how would I convert the dataReader.GetValue(1).ToString(); to the date format I want?
I have tried the following:
airportItems.ContractReceived_F = string.Format("{0:d}", dataReader.GetValue(1).ToString());
I am defining ContractReceived_F as string:
public string ContractReceived_F { get; set; }
and it still returned the time.
Use this:
airportItems.ContractReceived_F = dataReader.GetDateTime(1).ToString("yyyy-MM-dd");
where yyyy represents the year, MM represents the month and dd represents the day.
why not parse the data you need to like this
DateTime unparsed_date = mydatevalue; //any date in any date format
string parsed_date = unparsed_date.toString("dd mm yyyy");
Theres an article on the different parses on msdn that i found for you
check it out
Credit goes to fubo for the link (thumbs up)
I suggest to use the TryParseExact
Then you choose the date format that you need
For example :
DateTime OutputDate = null;
DateTime.TryParseExact(DateFromTheView, "yyyy/MM/dd H:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
In the example : the format is "yyyy/MM/dd H:mm:ss tt" and the input date string is DateFromTheView. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.

date time format issues in C#

I am attmepting to change a date time format for a search from ddd MMM dd HH:mm:ss zzz yyyy to just simply yyyy-MM-dd i'm not able to get the syntax right in my conversion so any help would be great.
public DateTime CreatedAt
{
get
{
return DateTime.ParseExact(this.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
}
}
public DateTime SearchDate
{
get
{
return DateTime.ParseExact(CreatedAt.ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
}
searchDate is my issue.
This won't work:
return DateTime.ParseExact(CreatedAt.ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
because CreatedAt.ToString() is going to create a date time string in the default format (not yyyy-MM-dd, which is how you're trying to read it).
But more importantly, why are you trying to convert a date from one string format time to another? If you have the DateTime value (CreatedAt, in this case), you can render it however you want (e.g. CreatedAt.ToString("yyyy-MM-dd")) There just doesn't seem to be any sense in converting it to a string and parsing parts of it.
And as Bob pointed out, if all you want is the date portion, take CreatedAt.Date. Try to think about what your real goal is, though and try to take the shortest route with the fewest conversions (and therefore conversion problems) as possible.

Convert string to Time

I have a time that is 16:23:01. I tried using DateTime.ParseExact, but it's not working.
Here is my code:
string Time = "16:23:01";
DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);
lblClock.Text = date.ToString();
I want it to show in the label as 04:23:01 PM.
"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:
DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture);
(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)
If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:
lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
Or better yet (IMO) use "whatever the long time pattern is for the culture":
lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);
Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.
(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.
The accepted solution doesn't cover edge cases.
I found the way to do this with 4KB script. Handle your input and convert a data.
Examples:
00:00:00 -> 00:00:00
12:01 -> 12:01:00
12 -> 12:00:00
25 -> 00:00:00
12:60:60 -> 12:00:00
1dg46 -> 14:06
You got the idea...
Check it https://github.com/alekspetrov/time-input-js

DateTime Format - Getting System.FormatException in c#

I am very new to C#.. I am writing an appointment schedule program where in I want to provide Date and Time value as a string from console and then I want to parse it to DateTime format. But by doing so I am getting
"System.FormatException" - string was not recognized as a valid datetime
Here is my piece of code,
string Format = "dd/MM/yyyy hh:mm tt";
Console.WriteLine("Enter the appointment date and time in(dd/MM/yyyy hh:mm AM/PM) format");
User_Input = Console.ReadLine();
Date_Time = DateTime.ParseExact(User_Input,Format,CultureInfo.InvariantCulture);
When I provide input exactly as format i.e like 23/11/2012 08:30 pm.. I am getting the said exception. I want to output datetime with AM/PM. What have I done wrong?
The question is a little bit odd since your format string works with your given input string(in all cultures) and you want to output with the same format. Perhaps somebody entered 23/11/2012 18:30 pm instead which does not work with the AM/PM designator.
string format = "dd/MM/yyyy hh:mm tt";
DateTime dateTime = DateTime.ParseExact("23/11/2012 08:30 pm", format, CultureInfo.InvariantCulture);
string output = dateTime.ToString(format, CultureInfo.InvariantCulture);
outputs: 23/11/2012 08:30 PM
demonstration
Note that you can always use DateTime.TryParseExact to validate user input.

how to get desired datetime format

i want to generate current date and time in a format like this Mon, 10/08/12 12:29:39 . But when i used a code shown below
DateTime date = DateTime.Now;
i am getting like 10/8/2012 12:29:39 PM , but i actually want a format like Mon, 10/08/12 12:29:39 , what change in this code i can use to get the desired output.
I did this code also ,but didnt success
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
Console.WriteLine(time.ToString("ddd, MM/dd/yy hh:mm:ss"));
string format = "ddd, MM/dd/yy HH:mm:ss";
Don't forget to provide the Culture (or the InvariantCulture) as a formatting parameter. Otherwise it will default to the UI culture which might not always provide the format that you expect.
string format = time.ToString("ddd, MM/dd/yy hh:mm:ss", CultureInfo.InvariantCulture);
you should read this page for the future
Custom Date and Time Format Strings:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
you can use this code for all detail datetime
string inp;
DateTime inpdate = DateTime.ParseExact(inp, "dd/mm/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
and u too use this code for with out time
ret = pc.ToDateTime(Convert.ToInt32(inp.Split('/')[2]), Convert.ToInt32(inp.Split('/')[1]), Convert.ToInt32(inp.Split('/')[0]), 0, 0, 0, 0);
You can specify the format either by using one of the built in Methods for example:
.ToShortDateTimeString();
or specifying a string format in the parameter of the .ToString() method.
Example:
.ToString("hh/MM/yyyy");
you can find all the available string formats on the MSDN page, or if you simply google it.

Categories