I have a system that outputs dates in the format "1{yy}{MM}{dd}" and I am trying to find a good way to parse it back into a real date.
At the moment I am using this:
var value = "1110825";
var z = Enumerable.Range(1,3).Select(i => int.Parse(value.Substring(i, 2))).ToList();
var d = new DateTime(2000 + z[0], z[1], z[2]);
but I'm sure there's a cleaner/more efficient way to do it?
I've tried DT.ParseExact, but can't find a suitable format string to use.
This works for me:
using System;
using System.Globalization;
public class Test
{
static void Main()
{
var value = "1110825";
DateTime dt = DateTime.ParseExact(value, "1yyMMdd",
CultureInfo.InvariantCulture);
Console.WriteLine(dt);
}
}
(You may want to use TryParseExact of course, if you need to cope with invalid data in any way other than with an exception.)
A slight variation of this is the format pattern of "'1'yyMMdd" - note the apostrophes round the 1. That quotes the 1 to force it to be treated as a "literal" in the pattern. It's not important in this case, but if you actually had values such as "y110825" then you'd want to quote the y to make sure it wasn't treated as part of a year specifier.
you can use DateTime.ParseExact:
here is a example for 12/26/1979:
var parseback = DateTime.ParseExact("1791226", "1yyMMdd",
System.Globalization.CultureInfo.CurrentCulture);
Use DateTime.ParseExact(string s, string format, IFormatProvider provider)
an example
DateTime.ParseExact("1110825", "1yyMMdd", CultureInfo.InvariantCulture);
Just use this code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DateTimeConvert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text= ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1]+" "+sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
}
}
Related
so i am making an WPF application where you insert PDF files and it will convert to text, after that a few Regex functions will be used on the text to give me only the important parts of the pdf.
the first problem i am running into is with numbers, if the number for example is 6.90 it will come out as 6.9. I have tried changing my Regex but it wont make a difference.
the second problem i have is when with dates for example 09-06-2022 it just wont write anything i have also tried changing the Regex but it just wont show up.
anyone know why this is ?
this is a line in the PDF i use i am trying to only get 6.90
Date: 06-09-2022 € 5.70 € 1.20 € 6.90
this is the Regex is use to only get the Amount
(?<=Date\:?\s?\s?\s?\d{0,2}\-\d{0,2}\-\d{0,4}\s?\€\s\d{0,10}\.?\,?\d{0,2}\s?\€\s\d{0,10}\,?\.?\d{0,10}\s?\€\s)\d{0,10}\.\d{0,2}
this is the Regex i use to only get the Date
(?<=Date\:?\s?\s?\s?)\d{0,2}\-\d{0,2}\-\d{0,4}
There are a lot of "?" in it because i have to make it compatible to multiple different PDF
screenshot of the outcome for the number in my selfmade Regex executor application
screenshot of the outcome for the date in my selfmade Regex executor application
screenshot of the outcome i get when i inserted a PDF
as you can see in the screenshots for some reason i get different results and i have no clue why its different
MainWindow
the button does all the work for recieving the pdf and changing it to text and going thru the correct class where all the regex are.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
//ItextSharp is a tool i use in Visual Studio
public partial class MainWindow : Window
{
private List<IRegexPDFFactuur> _listRegexFactuur = new
List<IRegexPDFFactuur>();
public MainWindow()
{
InitializeComponent();
}
public void btnUpload_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
tbInvoer.Text = "";
var file = openFileDialog.FileName;
var text = File.ReadAllText(file);
PdfReader pdf_Reader = new PdfReader(file);
String tempPDFText = "";
for (int i = 1; i <= pdf_Reader.NumberOfPages; i++)
{
tempPDFText = tempPDFText +
PdfTextExtractor.GetTextFromPage(pdf_Reader, i);
}
var PDFText = tempPDFText;
_listRegexFactuur.Add(new PDFtest1Type());
foreach (var tempRegexFactuurType in _listRegexFactuur)
{
if
(tempRegexFactuurType.IsRegexTypeValidForPDF(PDFText))
{
var tempPDFdate = tempRegexFactuurType.GetPDFdate(PDFText);
var tempTotalamount = tempRegexFactuurType.GetTotalamount(PDFText);
tbInvoer.Text += $"PDF Date: {tempPDFdate}\r\n";
tbInvoer.Text += $"Total amount: {tempTotalamount}";
break;
}
}
}
}
}
Interface for Regex
string regexPDFname { get; set; }
string regexPDFdate { get; set; }
string regexTotalamount { get; set; }
bool IsRegexTypeValidForPDF(string argInput);
double? GetPDFdate(string argInput);
double? GetTotalamount(string argInput);
Class with implemented Interface for Regex
public string regexPDFname { get; set; } = #"(PDFtest1)";
public string regexPDFdate { get; set; } = #"(?<=Date\:?\s?\s?\s?)\d{0,2}\-\d{0,2}\-\d{0,4}";
public string regexTotalamount { get; set; } = #"(?<=Date\:?\s?\s?\s?\d{0,2}\-\d{0,2}\-\d{0,4}\s?\€\s\d{0,10}\.?\,?\d{0,2}\s?\€\s\d{0,10}\,?\.?\d{0,10}\s?\€\s)\d{0,10}\.\d{0,2}"
public bool IsRegexTypeValidForPDF(string argInput)
{
var tempMatch = Regex.Match(argInput, regexPDFname, RegexOptions.IgnoreCase);
if (!tempMatch.Success) return false;
if (tempMatch.Value == "PDFtest1") return true;
else return false;
}
public double? GetPDFdate(string argInput)
{
var tempMatch = Regex.Match(argInput, regexPDFdate, RegexOptions.IgnoreCase);
if (!tempMatch.Success) return null;
if (Double.TryParse(tempMatch.Value, out var tempPDFdate)) return tempPDFdate;
else return null;
}
public double? GetTotalamount(string argInput)
{
var tempMatch = Regex.Match(argInput, regexTotalamount, RegexOptions.IgnoreCase);
if (!tempMatch.Success) return null;
if (Double.TryParse(tempMatch.Value, out var tempTotalamount)) return tempTotalamount;
else return null;
}
This is much easier without Regex
string input = "Date: 06-09-2022 € 5.70 € 1.20 € 6.90";
string[] array = input.Split(new char[] {':', '€'});
DateTime date = DateTime.Parse(array[1]);
decimal amount1 = decimal.Parse(array[2]);
decimal amount2 = decimal.Parse(array[3]);
decimal amount3 = decimal.Parse(array[4]);
If you still want to use Regex, this is a much simpler solution
Date\:\s{0,}(\d{1,2}-?\d{1,2}-?\d{2}(?:\d{2})?).+(\d+\.\d+).+(\d+\.\d+).+(\d+\.\d+)
Breakdown
Date\:\s{0,} matches Date: followed by 0 or more spaces
(\d{1,2}-?\d{1,2}-?\d{2,4}) matches your date string accepting 1 or 2 numbers for month and day and 2 or 4 for year
.+(\d+\.\d+) matches any characters until it matches 1 or more numbers followed by . and 1 or more numbers. This is repeated 3 times to obtain the currency values
RegEx Storm Example
I'm new to C#, and I am supposed to be demonstrating creating arrays and processing the contents of the arrays. Whenever I press calculate I get the same numbers every time. I am not sure what I am missing? I changed double to decimals thinking that might help change things, but no matter what I try to fix it still comes up the same. Any help in this is appreciated. I also had to save a .txt file into the same folder as the bin/debug for this project. Im instructed that this is supposed to read the files content into the array of double or decimal. the folder just has a few numbers with decimals (1260.07, etc)
heres the code I have so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsAppAssignment6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void analyzeBtn_Click(object sender,System.EventArgs e)
{
string file = "Sales.txt";
string salesValue;
Decimal[] sales = new decimal[7];
int count = 0;
decimal maxSales = Decimal.MinValue;
decimal minSales = Decimal.MaxValue;
decimal totalSales = 0;
try
{
StreamReader dataStream = new StreamReader(file);
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
sales[count] = Convert.ToDecimal(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
salesValue = dataStream.ReadLine();
}
dataStream.Close();
for (int item = 0; item < 7; item++)
salesListBox.Items.Add(sales[item]);
totalLbl.Text = totalSales + "";
avgLabel.Text = totalSales + "";
highSalesLabel.Text = maxSales + "";
smallSalesLabel.Text = minSales + "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}'''
Heres what populates every time.
The problem I think is with your error handling or the format of your document. Convert will actually throw an exception which will kill your entire loop if it cannot parse the current line. Say you had a simple line break in your file that created an empty line, you would try to parse it, an error is thrown, your code does nothing after it. Since I didnt have your file and I really do not feel like using visual studio instead of vscode, I replaced your streamreader with a stringreader (reads a string instead of a file but almost exactly the same) and i replaced the form with simple console writes. Outside of those changes, I gave myself some extra room in the array size since it was throwing exceptions and i wrapped the inside of the while loop in a try catch for format exceptions which is what Convert throws. After I made those changes, the outputs all worked properly. If you still dont see the values, then it is a problem with how you are using windows forms not your codes logic itself.
public static void Main()
{
Console.WriteLine("Hello World");
analyzeBtn_Click();
}
public static string SalesTxt = #"
1260.07
4002.52
267.21
15773.223
66655.2
555.0
7322
";
private static void analyzeBtn_Click()
{
string salesValue;
Decimal[] sales = new decimal[8];
int count = 0;
decimal maxSales = Decimal.MinValue;
decimal minSales = Decimal.MaxValue;
decimal totalSales = 0;
try
{
StringReader dataStream = new StringReader(SalesTxt);
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
try {
sales[count] = Convert.ToDecimal(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
} catch (FormatException) {Console.WriteLine("\tException: '"+ salesValue + "'"); }
salesValue = dataStream.ReadLine();
}
dataStream.Close();
string listItems = string.Join(",\n", sales);
Console.WriteLine(listItems);
Console.WriteLine(totalSales);
Console.WriteLine(maxSales);
Console.WriteLine(minSales);
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
Output:
Hello World
Exception: ''
Exception: ' '
1260.07,
4002.52,
267.21,
15773.223,
66655.2,
555.0,
7322,
0
95835.223
66655.2
267.21
EDIT:
In light of discussion, I have moved the string into a file with the appropriate name and used StreamReader just as you originally did. Using the same code as above just slightly modified, I was still able to get the correct output.
Below is my code where I intend to populate entity data via reflection.
public static void SetEntityProperty(object entity, DevExpress.Web.ASPxFormLayout formLayoutControl)
{
if (formLayoutControl != null)
{
Type type = entity.GetType();
System.Reflection.PropertyInfo[] properties = type.GetProperties();
System.Data.DataTable dt = new System.Data.DataTable();
foreach (System.Reflection.PropertyInfo pi in properties)
{
var layoutItem = formLayoutControl.FindItemByFieldName(pi.Name);
if (layoutItem != null && layoutItem.CssClass == "ro-item") continue;
var control = formLayoutControl.FindNestedControlByFieldName(pi.Name);
if (control != null && control is DevExpress.Web.ASPxEdit)
{
var targetType = Data.IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType;
try
{
if ((control as DevExpress.Web.ASPxEdit).Value != null)
{
//here (control as DevExpress.Web.ASPxEdit).Value = "19/05/2015" and control is a read only text box
var value = Convert.ChangeType((control as DevExpress.Web.ASPxEdit).Value, targetType);
if (value != null && value is System.String)
{
value = value.ToString().Trim();
(control as DevExpress.Web.ASPxEdit).Value = value;
}
pi.SetValue(entity, value, null);
}
else
{
pi.SetValue(entity, null, null);
}
}
catch (Exception ex)
{
pi.SetValue(entity, value, null);
}
}
else
throw ex;
}
}
}
What am I doing wrong here? I found few other questions related to Convert.ChangeType but all of there suggestions were already implemented into this code. I am using Visual Studio 2013 C#, DevExpress 14.2.6. Please help. Thanks.
Try this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace DateTimeConvert
{
class Program
{
static void Main(string[] args)
{
var text1 = "19/05/2015"; //dd/mm/yyyy format
var text2 = "05/19/2015"; //mm/dd/yyyy format
var result = DateTime.Now;
DateTime.TryParse(text1, out result);
Console.WriteLine(result);
DateTime.TryParse(text2, out result);
Console.WriteLine(result);
//Depending on computer's current culture format this will cause an error due to dd/MM/yyyy CULTURE format
//DateTime date = (DateTime)Convert.ChangeType(text1, typeof(DateTime));
var date = DateTime.ParseExact(text1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Console.ReadLine();
}
}
}
What happen is that you are converting a date time format of "dd/MM/yyyy". Which depends on your computer's Culture Format. You can use DateTime.ParseExact to instruct the correct format using CultureInfo.InvariantCulture.
Don't make a habit out of swallowing exceptions, or even handling exceptions that you don't know about.
In this case your application is very likely unable to parse the provided date.
Don't use the Convert class to parse text strings. Use Parse methods instead.
var resultDate = DateTime.ParseExact(((Control)DevExpress.Web.ASPxEdit).Value, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture)
My purpose on this is to insert a autonumber for this format AN-00000000 to the db, with the type in db varchar.
my code in windows form is saving a integer number already "10000000".
But I turn on my mind and think if possible that the auto number will be like this AN-00000000 and to save to the db with a character string.
I tried my best to change and apply but suddenly I can not implement because is on the integer part.
I am creating the basic system in our company to create a automate membership for the members, in our company we have 4 parts of membership which is Dep, sep, mep and cef, so I turn on my mind that i need to implement the 4 Id with the following to identify what the department they included. like DEP-00000001, SEP-00000001, MEP-0000001 and CEF-00000001.
Can anyone suggest or give their opinion on my code below? Thanks!
DBconnect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace PAIRDevelopment.Classes
{
public class DBConnect
{
public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);
public MySqlCommand cmdCon = new MySqlCommand();
public MySqlDataReader reader;
public void nonQuery(string cmdText)
{
cmdCon.Connection = csCon;
csCon.Open();
cmdCon.CommandText = cmdText;
cmdCon.ExecuteNonQuery();
cmdCon.Dispose();
csCon.Close();
}
public void OPEN(string cmdtext)
{
cmdCon.Connection = Classes.DBConnect.csCon;
Classes.DBConnect.csCon.Open();
cmdCon.CommandText = cmdtext;
reader = cmdCon.ExecuteReader();
}
public void CLOSE()
{
reader.Close();
cmdCon.Dispose();
Classes.DBConnect.csCon.Close();
}
}
}
Windows Form:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace PAIRDevelopment
{
public partial class Pair_Individual : Form
{
Classes.DBConnect OpenConCls = new Classes.DBConnect();
public Pair_Individual()
{
InitializeComponent();
textBox6.MaxLength = 13;
}
private void benabled_Click(object sender, EventArgs e)
{
OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");
while (OpenConCls.reader.Read())
{
string pcount = OpenConCls.reader[0].ToString();
if (pcount.Length == 0)
{
textBox1.Text = "10000000";
}
else
{
//int pcount1 = Convert.ToInt32(pcount);
//int pcountAdd = pcount1 + 1;
int pcount1 = Convert.ToInt32(pcount);
int pcountAdd = pcount1 + 1;
textBox1.Text = pcountAdd.ToString();
}
}
OpenConCls.CLOSE();
}
int pcount1 = Convert.ToInt32(pcount);
You are probably throwing a FormatException on the above line now if the string contains more than 0-9.
FormatException - value does not consist of an optional sign followed by
a sequence of digits (0 through 9).
If you know the first 4 chars will always be "XXX-" (e.g. "MEP-") then why don't you:
int pcount1 = Convert.ToInt32(pcount.Substring(4)); // ######## part
int pcountAdd = pcount1 + 1; // ######## + 1
textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
Which will convert only the numeric part, increment it, and then concatenate it with the first part.
Also you can look into the TryParse method. Which will indicate if your parse succeeded.
TryParse - Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation succeeded.
Hi I trying to get the max timedate from a table using LinqToSQL. I already asked a similar question, but was trying to do something a bit more specific, and no one was able to help. This time, i would not mind using any solution, short of an Execute SQL task in another part of the SSIS package. This is my whole code. I was trying just to get the Identity column and it wasnt even working, so ignore the ToString please if it seems out of place. I just want to get the latest CREATED_TIMESTAMP please
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Data.SqlClient;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace ST_663004ffff194a14b84e2291578ada33.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
//Strings for connections
string iFileName;
string oFileName;
string RW;
public void Main()
{
Dts.Variables["latestTableRow"].Value = getLatest();
MessageBox.Show(getLatest());
Dts.TaskResult = (int)ScriptResults.Success;
}// End Main
public string getLatest()
{
string result = "";
////temp dummy/defaul date is two days ago
//DateTime result = new DateTime();
//result = DateTime.Now.AddDays(-2);
try
{
//get the data connection string from the connection manager
RW = (string)Dts.Connections["ReportingWarehouse"].ConnectionString;
//Remove the Provider, Auto Translate, and Application
//as it is not a parameter for the DataContext constructor
RW = RW.Remove(RW.IndexOf("Provider=SQLNCLI10.1;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Auto Translate=False;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Application"),RW.Length - RW.IndexOf("Application"));
MessageBox.Show(RW);
//get the last insertion date from the SSASLoging table
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
orderby r.TimeStamp descending
select r).Max();
result = rs.Errorval.ToString();
}
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show("Exception in retreiving latest time: " + e.Message + "/n"
+ e.StackTrace);
}
return result;
}
}//end partial class
[Table(Name = "SSASLogging")]
public class SSASLogging
{
private DateTime timeStamp;
[Column(Name = "CREATED_TIMESTAMP")]
public DateTime TimeStamp
{
get { return this.timeStamp; }
private set { ;}
}
}//End SSASLogging
}
Ok this works
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
select r).Max(r => r.TimeStamp);
result = rs;
}