How to convert date to 'ccyymmddhhmmss' format? - c#

How to convert date to 'ccyymmddhhmmss' format in c#?

You might want to try this... I don't know if cc is included, so I solved for the cc.
DateTime time = DateTime.Now;
string format = "yyMMddhhmmss";
Console.WriteLine(((Convert.ToInt32(time.ToString("yyyy")) / 100) + 1).ToString() + time.ToString(format));
For "yyMMddhhmmss".....Try this...And don't forget that capital M is Month and lower case m is minutes.
DateTime dt = Convert.ToDateTime("8 Oct 10 19:00");
Console.WriteLine(dt.ToString("yyMMddhhmmss"));

From what I understand from your question, you want to format a c# date object to the specified format?
The easiest way to do that is by using the date.ToString("yyyyMMddHHmmss") - where date is the Date Object... There are several choices to this - like having 12-hour instead of 24-hour etc. The best option is to read through http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and set what you need.
Hope this helps.

#Chris_techno25: I took the freedom to extend your answer:
If we stick to the question of Narashima, he wants the format ccyymmddhhmmss.
So I've scratched up this extension method:
public static string IncludeCentury(this DateTime sourceDate, bool replace)
{
var source = String.Format("{0}/{1}", sourceDate.Year / 100 + 1, sourceDate);
if(replace)
return Regex.Replace(source, "[^0-9]", "");
else
return source;
}
Usage:
var includingCentury = DateTime.Now.IncludeCentury(true)
var includingCentury = DateTime.Now.IncludeCentury(false)
Output:
21218201491410
21/2/18/2014 9:18:10 AM

Related

How to subtract DateTime field and Duration?

I have one field in database in this format: 2013-06-18 17:00:00.000
and second field Duration in this format: 3000 (this represents seconds, so it is 50 minutes)
I need to subtract those two fields and to set in another field result which will be: 2013-06-18 16:10:00.000
One addition is that they both can be retrieved from database in string format only. So they are both strings.
Thanks
First you need to Parse the datetime. Then subtract using AddSeconds:
var date = DateTime.Parse("2013-06-18 17:00:00.000");
var newDate = date.AddSeconds(int.Parse("-3000"));
You can use newDate.ToString() to get the date as a string.
You can find the documentation for DateTime here.
Update: Changed seconds to a string value. Which uses Parse to convert to an integer.
You can subtract to the datetime object. (if is a DateTime Type) if not, you should parse.
To handle errors, I would recommend to use DateTime.tryParse(value, out dateTime);
DateTime parsedDateFromBD;
if(DateTime.tryParse("2013-06-18 17:00:00.000", out parsedDateFromBD)
{
// do Stuff
}
else
{
// do something else
}
if you get it as a datetime from the db you can simply:
var calcDate1 = dateFromBD.addSeconds(3000); //to Add
var calcDate2 = dateFromBD.addSeconds(-3000); //to subtract
Cheers
Ricardo
In addition to the other answers here is how to parse the newDate to string that mach the required output
string date = "2013-06-18 17:00:00.000";
string duration = "-3000";
int durationSeconds = int.Parse(duration);
var newDate = DateTime.Parse(date).AddSeconds(durationSeconds).ToString("yyyy-MM-dd HH:mm:ss.fff");
The output is
//2013-06-18 16:10:00.000
Here you can find more about DateTime.ToString()

c# convert PDF metadata CreationTime to DateTime

I need to process the CreationTime I retrieve from the PDF's metadata and compare it to DataTime format.
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
This returns a Date-Time-String like:
D:20150710080410
D:20150209075651+01'00'
and to compare:
DateTime Created = Convert.ToDateTime(CreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
Martin
I really needed a solution for this, BBL Admin 's Comment on writing your own function turned out to be my way out.
From this [this itex support link][1] I was able to get the intepratation of the pdfDate format as D:YYYYMMDDHHmmSSOHH'mm'
Next thing I needed to know is the supportade date formats in c# that I may Parse using DateTime.Parse() from [this c-sharpcorner artical][2] and the most ideal for me was "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss"
Having known the input I get and the format I can parse, I created the function below to construct the date, basically getting parts from the pdfDate and building parts for the 'parsable' date string...
private DateTime CreateDateTime(string date) //use the pdfDate as parameter to the date argument
{
string dateStr = date.Remove(0, 2).Remove(14, 6); //Remove D: & OHH'mm
string tmpDateStr = dateStr.Substring(0, 4) //Get year i.e yyyy
+ "-" + dateStr.Substring(4, 2) // Get month i.e mm & prepend - (hyphen)
+ "-" + dateStr.Substring(6, 2) // Get day i.e dd & prepend -
+ "T" + dateStr.Substring(8, 2) // Get hour and prepend T
+ ":" + dateStr.Substring(10, 2) // Get minutes and prepend :
+ ":" + dateStr.Substring(12, 2); //Get seconds and prepend :
return DateTime.Parse(tmpDateStr);
}
Well, I hope you found a way at the time of asking, anyone else facing the same challange could try my approach and see if it helps. Nevertheless, question answered.
NB: There could be other/better ways to do it.
[1]: http://itextsupport.com/apidocs/iText7/7.1.0/com/itextpdf/kernel/pdf/PdfDate.html
[2]: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
If your Date-Time string that you're trying to convert is going to start with "D:" every time, then you might think about adding in a remove function for D:. That's what's probably giving you the exception when you try to convert. Try this:
// Gather the Info
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
string sCreatedDate = Convert.ToString(CreatedDate).Remove(0, 2)
// Convert and Compare
DateTime Created = Convert.ToDateTime(sCreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
You don't have to create sCreatedDate, but it's a little bit cleaner to view it that way. You could also convert CreatedDate.ToString().Remove(0,2) when you do the datetime convert:
DateTime Created = Convert.ToDateTime(CreatedDate.ToString().Remove(0,2));
Hope this helps.

Parse date format to DateTime c#

How to parse this string:
"\"2014-01-02T23:00:00.000Z\"" to DateTime
This didn't work:
DateTime? dateTimeFormat= string.IsNullOrEmpty(inputString) ?? (DateTime?)null : DateTime.Parse(inputString);
You need to specify exact format of you datetime to the DateTime.ParseExact method:
string input = "\"2014-01-02T23:00:00.000Z\"";
var date = DateTime.ParseExact(input, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'", null);
Description of format provided:
'\"' - match first "
yyyy-MM-dd - match 2014-01-02
'T' - match T
HH:mm:ss.fff - match 23:00:00.000
'Z\"' - match Z"
This will help
string test = "2014-01-02T23:00:00.000Z";
DateTime dt = Convert.ToDateTime(test);
DateTime.ParseExact(your_date.ToString(), "yyyy-MM-ddTHH:mm:ssZ", null)
Reformat the string to put in the proper format, then parse
string = "\"2014-01-02T23:00:00.000Z\"";
string = substring(3,10) + " " + substring(14,8); //"2014-01-02 23:00:00"
time = DateTime.Parse(string);
Try This:
DateTime.ParseExact("2014-01-02T23:00:00.000Z" , "yyyy-MM-DDThh:mm:ssZ",CultureInfo.InvariantCulture);
Maybe this might work.
Add-
using System.Globalization;
I've tried almost all of the method/codes in this answer but none of them worked for me. Although, using parts of code of previous answer to this question, I did this and it worked perfectly for me.
var d = "2019-01-11T05:00:00.000Z"; //Date
int year = Convert.ToInt32(d.Substring(0, 4));
int month = Convert.ToInt32(d.Substring(5, 2));
int day = Convert.ToInt32(d.Substring(8, 2));
var time = new DateTime(year, month, day);
I was not concerned with the time. You can add it if you want.

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

I want to show in a TextBox only hour and minutes
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
how to show only hours and minutes "hh.mm"
You need to convert your data to TimeSpan and then use format:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(#"hh\:mm"));
In your case:
var test = dataRow.Field<TimeSpan>("fstart").ToString(#"hh\:mm"));
Remember to escape the colon :
You may see: Custom TimeSpan Format Strings
There is no need to convert from hh.mm.ss to hh.mm. TimeSpan is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the TimeSpan into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case hh.mm.ss.
string formatted = timespan.ToString(#"hh\.mm");
Note: This overload of ToString exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.
The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format(#"{0:hh\.mm}", timespan); // ==> 00:20:34
However, you can construct the string like this
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
or starting with VS2015 / C# 6.0, using string interpolation:
string formatted = $#"{timespan:hh\:mm}";
You can use TimeSpan methods:
ToString("hh':'mm")
// or
ToString(#"hh\:mm")
Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
I know this is a very old question. If anyone wants to show single-digit hours when your hours are a single digit then you can use
var hoursWithMinutes = TimeSpan.FromHours(hours).ToString(#"h\:mm")
This way, when your hours are double-digit I mean greater than 9 then it will be showing 10:00 something like that.
The previous solutions don't run if hours>24, try this solution if you have time in minutes very big
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;
You can achieve this by:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(#"hh\:mm")

how to achieve timespan to string conversion?

I tried searching here, but it couldn't help me much ..
I want to convert time_span to string, I don't want to return the timespan in days .. but only HH:mm:ss. How to achieve that?
My sample code is here:
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString("HH:mm:ss");
Try using
DateTime d = new DateTime(time_span.Ticks);
string time = d.ToString("HH:mm:ss");
This should work:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString(), time_span.Minutes.ToString(),
time_span.Seconds.ToString());
As per comment if you want the double digits you could do:
string temp = string.Format("{0}:{1}:{2}",
time_span.Hours.ToString("00"), time_span.Minutes.ToString("00"),
time_span.Seconds.ToString("00"));
Edited:as per jimmy's comment,
string temp = string.Format("{0:00}:{1:00}:{2:00}",time_span.Hours, time_span.Minutes, time_span.Seconds);
Try this:
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString();
temp = string.Format("{0}:{1}:{2}", time_span.TotalHours, time_span.TotalMinutes, time_span.TotalSeconds);
Edit
After I read your comment on your question, that is you need to display zero hours for new days, my answer will give you total hours, minutes and seconds, not what you want.
(+1) Kelseys ;)
The code I have implemented is:
string temp = DateTime.Today.Add(time_span).ToString("HH:mm:ss");
Originally posted by Marc Gravell,
There is a much simpler way of doing this now (albeit only using framework 4), you just need to use the string literally, and you can do it directly on the TimeSpan instance.
time_span.ToString(#"hh\:mm\:ss")
That will output
00:26:39
Helpful now for people stumbling across this (like myself).
Cheers :)
Simply convert the value of ticks into a DateTime and then use its ToString()
var date1 = DateTime.Now;
var date2 = DateTime.Now.AddSeconds( -1000 );
var diff = date1 - date2;
var temp = new DateTime( diff.Ticks ).ToString( "HH:mm:ss" )
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
TimeSpan finalTime = (time_span_var + time_span);
Console.WriteLine(finalTime);
Console.WriteLine(finalTime - TimeSpan.FromHours(finalTime.Days * 24));
If the number of days is irrelevant then you have the solution, however I came across this answer searching for a conversion that gave hours in total, so 36 hours would need to be displayed as 36:00:00. Using some of the hints above this is what I came up with:
SomeLabel.Text = Math.Floor(ts.TotalHours).ToString() + ":" + ts.Minutes.ToString("D2") + ":" + ts.Seconds.ToString("D2");
Total Hours is always rounded down, minutes and seconds are padded to be 2 digits (00 - 09)

Categories

Resources