My C# is very limited and my english too. I need your help. I need to edit the data from the barcode reader. Incoming data like this.
1-) 12345678 (Barcode)
2-) 310319 (Date d m y format)
3-) 174252 (Hour minute second)
4-) 123 (Barcode)
5-) 010419 (Date d m y format)
6-) 153020 (Hour minute second)
7-) 3873 (Code)
Ok this is my data from the barcode reader. I want to format this data as follows.
the final output is sample like this. Sorry for my bad english can you help me please
1-) 12345678 (Barcode not change)
2-) 2 and 3 lines to timestamp ( 310319 + 174252) ? to timestamp
3-) 123 (Barcode not change)
4-) 5 and 6 lines to timestamp (010419 + 153020) ? to timesatamp
5-) 3873 (not change)
string name = lvw.SubItems[1].Text = Splt[0];
string filePath = #"C:\Temp\data.csv";
var one = lvw.SubItems[1].Text = Splt[0];
var two = lvw.SubItems[1].Text = Splt[1];
var three = lvw.SubItems[1].Text = Splt[2];
var four = lvw.SubItems[1].Text = Splt[3];
var five = lvw.SubItems[1].Text = Splt[4];
var six = lvw.SubItems[1].Text = Splt[5];
var seven = lvw.SubItems[1].Text = Splt[6];
var data = one +";" + two + ";" + three + ";"
+ four + ";" + five + ";" + six + ";" + seven + Environment.NewLine;
File.AppendAllText(filePath, data);
variable two + three combine to timestamp this is my problem ?
#Henk Holtermans answer works pretty well with the question you asked, since you didn't determine what a timestamp is in your case.
I'm just gonna answer to add some DateTime usage, since it may be useful for you in the future.
First, convert the strings to a DateTime object:
string date = "310319";
string time = "174252";
DateTime dt;
string timestamp;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
if(correct){
timestamp = dt.ToString("yyyyMMddHHmmssffff");
}
TryParse lets you get a boolean result of your conversion, meaning that you don't need to check for errors, just ifthe result is true.
TryParseExact lets you tell the function exaclty how is your string formed
Here you can see a list os custom format strings
out dt is where the converted datetime is gonna get stored
After that I'm checking if the result boolean and if the conversion was successful I'm getting a timestamp string of the DateTime object.
"yyyyMMddHHmmssffff" is the output format of the string, where yyyy is the year in 4 chars, MM the month in 2 chars and so on. You have every possible custom string in the link I already provided.
string date = "310319";
string time = "174252";
DateTime dt;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
Console.WriteLine(dt);
DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
dto = new DateTimeOffset(dt, TimeSpan.Zero);
long y = dto.ToUnixTimeSeconds();
Console.WriteLine(y); // output 1554054172
thank you to everyone. That's how I solved my problem.
Related
The test i did is:
string date = DateTime.Now.ToString("ddd dd.MM.yyyy");
string time = DateTime.Now.ToString("HH.mm tt");
string format = "{0} from {1} At {2}";
string cp = string.Format(format, "", date, time);
Directory.CreateDirectory(#"c:\\temp\\" + cp);
The result in the variable cp is: from Fri 20.01.2017 At 09.27 AM
And there is no problem to create this directory.
This is my code:
for (int i = 0; i < countriesNames.Count(); i++)
{
string pathDateTime = urls[0].Substring(48, 12);
string pathDateTimeLast = urls[urls.Count - 1].Substring(48, 12);
var d = DateTime.ParseExact(pathDateTime, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
var e = DateTime.ParseExact(pathDateTimeLast, "yyyyMMddHHmm", CultureInfo.InvariantCulture);
string country = countriesNames[i].Substring(15);
string f = "{0} from {1} At {2} until {3}";
string countryPath = countriesMainPath + "\\" + country + "\\" + string.Format(f, "", d,e);
if (!Directory.Exists(countryPath))
{
Directory.CreateDirectory(countryPath);
}
countryPaths.Add(countryPath);
}
The way i did it with the 'f' variable is not right and not working fine give me exception.
In my code in the variable 'd' there is 20/01/2017 05:15:00
And in variable 'e' 20/01/2017 07:30:00
But i can't create this directories.
So i want to format my date and time after extracting them to be like the format in the first example: from Fri 20.01.2017 At 09.27 AM but with my date and time.
For example my directory should be something like:
from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM
Then to create this directory: "from Fri 20.1.2017 At 05:15 AM Until 20.1.2017 At 07:30 AM"
The question is how do i format my dates and times after parsed to this format ?
You are trying to create a path by formatting dates using your current locale's default (long) format. In most countries the date separator is / and the time separator is always :. This results in invalid paths.
It's a bit hard to understand what format you want to use, since you mix calls to String.Format and concatenate the results. It seems that the original path should be:
var cp=String.Format(#"c:\temp\From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now);
or
var root="c:\temp\";
var partialPath = String.Format("From {0:ddd dd.MM.yyyy} At {0:HH.mm tt}",DateTime.Now)
var cp=Path.Combine(root,partialPath);
You don't need to format each component separately. If you check the documentation of String.Format you'll see that you can use a composite format string for each placeholder.
The country path seems to be
var partialPath = String.Format(#"{0}\from {1:ddd dd.MM.yyyy} At {1:HH.mm tt} until {2:HH.mm tt}",
country,d,e);
var countryPath =Path.Combine(countriesMainPath,partialPath);
That said, I wouldn't use that date format. The resulting folder names can't be sorted in a meaningful way making it difficult for users to find folders by date. I'd use the yyyy-MM-dd format, or yyyy-MM-dd ddd if the name of the day is really necessary.
I'm trying to use both System.DateTime.Now.ToString() and Convert.ToDateTime and was running into some strange behavior. I have narrowed down the problem to the Convert.ToDateTime. For some reason a DateTime type set with System.DateTime.Now is not the same as one that has been converted from a string. However when you output either of them they appear to be the same.
(I have tried using Trim(), TrimStart(), and TrimEnd() to no avail.)
This is the output in console after running this in unity:
http://imgur.com/1ZIdPH4
using UnityEngine;
using System;
public class DateTimeTest : MonoBehaviour {
void Start () {
//Save current time as a DateTime type
DateTime saveTime = System.DateTime.Now;
//Save above DateTime as a string
string store = saveTime.ToString();
//Convert it back to a DateTime type
DateTime convertedTime = Convert.ToDateTime(store);
//Output both DateTimes
Debug.Log(saveTime + "\n" + convertedTime);
//Output whether or not they match.
if (saveTime == convertedTime)
Debug.Log("Match: Yes");
else
Debug.Log("Match: No");
//Output both DateTimes converted to binary.
Debug.Log(saveTime.ToBinary() + "\n" + (convertedTime.ToBinary()));
}
}
You lose a lot when you convert a DateTime to a string via DateTime.ToString().
Even if you include the milliseconds like this:
DateTime convertedTime =
new DateTime(
saveTime.Year,
saveTime.Month,
saveTime.Day,
saveTime.Hour,
saveTime.Minute,
saveTime.Second,
saveTime.Millisecond);
you would still get a different DateTime that is not equal to the original one.
The reason for this is that internally a DateTime stores a number of ticks (since 12:00:00 midnight, January 1, 0001). Each tick represents one ten-millionth of a second. You need to get the same number of Ticks for the two DateTime objects to be equal.
So, to get an equal DateTime, you need to do this:
DateTime convertedTime = new DateTime(saveTime.Ticks);
Or if you want to convert it to a string (to store it), you can store the ticks as a string like this:
string store = saveTime.Ticks.ToString();
DateTime convertedTime = new DateTime(Convert.ToInt64(store));
The result of DateTime.ToString() does not include milliseconds. When you convert it back to DateTime, you basically truncate the milliseconds, so it returns a different value.
For example
var dateWithMilliseconds = new DateTime(2016, 1, 4, 1, 0, 0, 100);
int beforeConversion = dateWithMilliseconds.Millisecond; // 100
var dateAsString = dateWithMilliseconds.ToString(); // 04-01-16 1:00:00 AM (or similar, depends on culture)
var dateFromString = Convert.ToDateTime(dateAsString);
int afterConversion = dateFromString.Millisecond; // 0
I think you are losing your time zone during the ToString() method. So the re-converted DateTime ends up in a different time zone.
Check also the DateTime.Kind property.
I am working on a new project in c#, i have no experience with date and time.
Here i need to find the difference between two time values which is in string format
string pointavalue = comboBox1.Text + ":" + comboBox2.Text + ":" + comboBox5.Text;
string pointbvalue = comboBox3.Text + ":" + comboBox4.Text + ":" + comboBox6.Text;
string pointcvalue = comboBox7.Text + ":" + comboBox8.Text + ":" + comboBox9.Text;
DateTime pointa = DateTime.Parse(pointavalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointb = DateTime.Parse(pointbvalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointc = DateTime.Parse(pointcvalue, System.Globalization.CultureInfo.CurrentCulture);
string time1 = pointa.ToString("HH:mm:ss");
string time2 = pointb.ToString("HH:mm:ss");
string time3 = pointc.ToString("HH:mm:ss");
There is three Values pointavalue, pointbvalue. pointcvalue.
They are combined string values of comboboxes.
Now how do i subtract pointbvalues from pointavalues?
I know they are in string format so operations cannot be performed.
the code you are looking is not mine, someone helped me but its working as a expected.
I am learning C# so bear with me.
ok i think figure out something, but still i can't solve it.
Here is my recent work with the code
DateTime inputa = DateTime.Parse(label21.Text, System.Globalization.CultureInfo.CurrentCulture);
DateTime inputb = DateTime.Parse(label23.Text, System.Globalization.CultureInfo.CurrentCulture);
if (pointa < pointb)
{
TimeSpan diff1 = pointb.Subtract(pointa);
DateTime d1=Convert.ToDateTime(diff1);
if (d1 < inputa)
{
label34.Text = "fail";
}
else
{
label34.Text = "pass";
}
Here i want to check the condition of the time diff1 and inputa, that's it that's all i need to finish this project.
The reason why you can't solve this problem is that you are trying to compare two different data types, Timespan and Datetime are not same
Either convert all your string to "Timespan" (That is better option).
Datetime will give you the present date, but it seems you don't need that.
Last but not least learn some basics before you ask these questions.
One more simple example:
void Main()
{
DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
TimeSpan difference = yesterday - now;
Console.WriteLine (difference.GetType().Name);
Console.WriteLine (difference.TotalSeconds); // expecting -86400
}
running this will print
TimeSpan
-86400
Take a look at the DateTime.Substract method:
TimeSpan abdiff = pointb.Substract(pointa);
TimeSpan bcdiff = pointc.Substract(pointb);
Alternatively, you can use the - operator, you get back a Timespan which contains the differences:
TimeSpan abdiff = pointb - pointa;
TimeSpan bcdiff = pointc - pointb;
Assuming that your combo boxes contain the hour, minute, and second then you could do the following.
TimeSpan pointa = new TimeSpan(int.Parse(comboBox1.Text), int.Parse(comboBox2.Text), int.Parse(comboBox5.Text));
TimeSpan pointb = new TimeSpan(int.Parse(comboBox3.Text), int.Parse(comboBox4.Text), int.Parse(comboBox6.Text));
TimeSpan pointc = new TimeSpan(int.Parse(comboBox7.Text), int.Parse(comboBox8.Text), int.Parse(comboBox9.Text));
TimeSpan aTob = pointa > pointb
? pointa - pointb
: (pointa + TimeSpan.FromDays(1)) - pointb;
Basically this assumes that your combo boxes only have valid hour (0-23), minute (0-59), and second (0-59) values. Then you just need to determine if your times are on the same day or not. If you assume that pointa is latter than pointb then checking if it is greater than pointb means you can do a straight subtraction. If not then it must be the time for the next day and you just add 1 day to it before subtracting pointb.
This is based on your assertion that 01:00 - 23:00 should be 2 hours and not -22. Thought it would be best if there where a date included so you would know for sure if the times are on the same day or the next day or from completely different years.
I am trying to combine a DateTime from a number of combo boxes that i have on a form.
From this image you can see how the combo boxes are laid out.
Wondering what is the best way to do this currently i have the following but am not sure that it is correct.
string startdate = cmbMonthYear.Text + "-" + cmbMonth.SelectedIndex.ToString()+ "-" + cmbDay.Text + " "+ "07:00";
DateTime StartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
What is the best way that i could go about this?
A better way would probably be to avoid the parse exact and make sure you have the most accurate representation of the date you want, preferably in integers. You'll want to set the Value-parts of the items in your comboboxes as well. You can probably do that in the code that adds the items to those comboboxes.
So you'll have something like:
// Check your input here
// ...
int day = Convert.ToInt32(cmbDay.SelectedValue);
int month = Convert.ToInt32(cmbMonth.SelectedValue); // No need to have text in SelectedValue, just integer
int year = Convert.ToInt32(cmbMonthYear.SelectedValue);
DateTime StartDate = new DateTime(year, month, day, 7, 0, 0);
This should work (if you're sure about your input):
var date = new DateTime(int.Parse(cmbMonthYear.Text), cmbMonth.SelectedIndex, int.Parse(cmbDay.Text), 7, 0, 0);
Use the DateTime.TryParse method to also validate the input from the user. A good practice when sometimes you have textboxes instead of dropdownlists:
string startdate = cmbMonthYear.SelectedValue
+ "-" + cmbMonth.SelectedValue
+ "-" + cmbDay.SelectedValue
+ " 07:00";
DateTime StartDate;
if(!DateTime.TryParse(startdate, out StartDate){
//invalid date, show a warning message (e.g. lblErrors.Text = "Start Date is not valid!";)
}else{
//your date is parsed and valid :)
}
Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;