Problems with Datetime transform with SmartFormat for Net (C#)
SmartFormat is a is a lightweight text templating library to replace string.Format. Unlike common String.Format, with SmartFormat you can read templates from text files or another source. Here I will share the way, how I tried to write the DateTime in the format 'dd/MM/yyyy HH:mm:ss'. It was not so obvious.
The link to SmartFormat project is https://github.com/axuno/SmartFormat.
So, I wanted to write the Datetime value as 'dd/MM/yyyy HH:mm:ss'.
Obviously, the potential way to write the date is like this:
DateTime dateTime = DateTime.Now;
var smartFormat = Smart.Format("{0:dd/MM/yyyy HH:mm:ss}", dateTime);
But whatever I did, always got the error:
Unhandled exception. SmartFormat.Core.Formatting.FormattingException: Error parsing format string: No suitable Formatter could be found at 0
{0:dd/MM/yyyy HH:mm:ss}
at SmartFormat.Evaluator.FormatError(FormatItem errorItem, Exception innerException, Int32 startIndex, FormattingInfo formattingInfo)
at SmartFormat.Evaluator.InvokeFormatters(FormattingInfo formattingInfo)
at SmartFormat.Evaluator.WriteFormat(FormattingInfo formattingInfo)
at SmartFormat.SmartFormatter.ExecuteFormattingAction(SmartFormatter formatter, IFormatProvider provider, Format formatParsed, IList`1 args, IOutput output, Action`1 doWork)
at SmartFormat.SmartFormatter.FormatInto(IOutput output, IFormatProvider provider, Format formatParsed, IList`1 args)
at SmartFormat.SmartFormatter.Format(IFormatProvider provider, Format formatParsed, IList`1 args)
at SmartFormat.SmartFormatter.Format(IFormatProvider provider, String format, IList`1 args)
at SmartFormat.SmartFormatter.Format(String format, Object[] args)
at SmartFormat.Smart.Format(String format, Object arg0)
As I understood, the reason is that SmartFormat uses ':' as a system separator for variable and formatting. So, how to write the datetime in the required format.
The solution is easy but may be not very flexible.
var smartFormat = Smart.Format("{0:dd/MM/yyyy} {0:HH}{0:mm}{0:ss}", dateTime);
If you load the template from text file or database, use the next format
{ActionDate:dd/MM/yyyy} {ActionDate:HH}:{ActionDate:mm}:{ActionDate:ss}