In window, i can get the date created of the video from properties(right click). I have a few idea on this but i dont know how to do it. 1. Get the video information directly from video(like in windows),
2. By extracting the video name to get the date created(The video's name is in date format, which is the time it created). And i also using taglib-sharp to get the video duration and resolution, but i cant find any sample code on how to get the video creation date.
Note: video name in date format - example, 20121119_125550.avi
Edit
Found this code and so far its working
string fileName = Server.MapPath("//video//20121119_125550.avi");
FileInfo fileInfo = new FileInfo(fileName);
DateTime creationTime = fileInfo.CreationTime;
Output: 2012/11/19 12:55:50
For the file's name, i will add another string in name. For example User1-20121119_125550.avi.avi, so it will get complicated after that.
If you can safely trust your filenames, you may be content with the following:
string file_name = "20121119_125550.avi";
string raw_date = file_name.Split('.')[0];
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "yyyyMMdd_hhmmss";
DateTime result = DateTime.ParseExact(raw_date, format, provider);
Note: You'll likely need to add using System.Globalization; to any file you wish to use this in.
If you just want the date the file was created (What you see in Windows Explorer) you can just use:
string file_path = #"C:\20121119_125550.avi"; //Add the correct path
DateTime result = File.GetCreationTime(file_path);
Related
I have a file named test-2000_01_02-10_12_14.xml.
How do I only get the date from the file?
I was able to get the date if the file has this name: 2000_01_02-10_12_14
with this (b is a StorageFile):
DateTime dateVal;
bool parsed = DateTime.TryParseExact(b.DisplayName,
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal);
I then tried to change yyyy_MM_dd-H_mm_ss to something like this *-yyyy_MM-dd-H-mm_ss but it does not seem to be the solution
There are a boatload of ways to do this, it really rather depends on how regular the naming of your files is - is there always some junk text followed by a hyped, then the year?
Post up another 10 different examples if you want more tailored advice. Here's a way for the one you've posted:
DateTime.TryParseExact(
Path.GetFileNameWithoutExtension(b.DisplayName.Substring(b.DisplayName.IndexOf('-')+1)),
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal
);
This uses Substring with only one argument (no length) to remove everything after the first hyphen up to the end of the string, and GetFileNameWithoutExtension to remove the .xml - this effectively turns anythinghere-2000_01_01-00_00_00.xml into 2000_01_01-00_00_00 ready for parsing
I could also have gone for a .Remove("last index of period") type thing but it does get a bit messy because you have to subtract the start Index of the hyphen etc
MJWill's comment about splitting on hyphen is also a good one - you could split then take the [1] and [2] indexes and join then back together for parsing..
Lastly don't forget that the file itself might have a created date that is already a good candidate for the date of creation rather than the filename (which might be mangled by humans) so long as it hasn't been transmitted somewhere and re-saved. Take a look at the FileInfo.CreationTime property for that - https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8
First, we have to extract (match) the datetime part from a file name:
using System.Text.RegularExpressions;
...
// Aggravated task: dots and minuses within file's name
string source = #"bla-bla-bla-test.me-2000_01_02-10_12_14.xml";
string datetime = Regex.Match(
Path.GetFileNameWithoutExtension(source),
"[0-9]{4}_[0-9]{2}_[0-9]{2}-[0-9]{2}_[0-9]{2}_[0-9]{2}$").Value;
Then we can parse it
if (DateTime.TryParseExact(
datetime,
"yyyy_MM_dd-H_m_s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out DateTime result) {
// result is the parsed date
}
else {
// File doesn't contain valid date and time
}
I would suggest you to use regular expression assuming that your file name will be always following the same format you can do something like this:
var pattern = #"\d{4}_\d{2}_\d{2}-\d{2}_\d{2}_\d{2}";
var fileName = "test-2000_01_02-10_12_14.xml";
var match = new Regex(pattern);
var result = match.Match(fileName);
if (result.Success)
{
DateTime.TryParseExact(result.Value,
"yyyy_MM_dd-HH_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out DateTime dateVal);
}
I want to save to a specific space a single file at several states. So i thought about stamping it with the time of creation to tell one from another.
I have created a dummy program that goes through exactly the same procedure my full program does but concentrated.
Here is the code:
DateTime first = DateTime.Now;
long ft = first.ToFileTime();
string time = "" + ft;
long timeLong = Convert.ToInt64(time);
DateTime normalDate = DateTime.FromFileTime(timeLong);
string normalName = ""+ normalDate;
DateTime thisDate = DateTime.Parse(normalName);
long fit = thisDate.ToFileTime();
So it goes through those steps:
Create time and convert to long for file.
Save it as string inside the files name(i pass it like that but in "" is the files name)
Then i retrieve it, i cast it into long, to create a DateTime format readable for the human with FromFileTime.Then to string fro the user to read it in a comboBox.
Then the user selects and it becomes DateTime , to get into long through tge TiFileTime ( at this point i have the problem as it appears to loose everything smaller than seconds)
I want to cast it back into long at the end to be able to run through the files again and find the one that matches with the one that the user choose.
here is some output values:
Edit : As you can see form the results above. I miss something . The initial and the final values are not the same.So i cant find the same file again.
The Parse() method don't have all the information that the DateTime structure holds (you can find its members here).
string normalName = ""+ normalDate;
DateTime thisDate = DateTime.Parse(normalName);
Will not return the exact value (including Ticks) as the original one.
You should do it as follows, using Ticks:
string normalName = "" + normalDate.Ticks;
DateTime thisDate = new DateTime(long.Parse(normalName));
long fit = thisDate.ToFileTime();
I'd like to use Oracle date formatting in C#, such as in to_char(date, format), without database connection nor writing my own format interpreter.
Sample application (I'm using Oracle Data Provider for .NET):
namespace OracleDateToCharTest
{
using System;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
class Program
{
/// <param name="fmt"> Oracle-like format string. </param>
public static string OracleDateToChar(DateTime date, string fmt)
{
//// preparing format for ToString()
OracleGlobalization og = OracleGlobalization.GetThreadInfo();
string prevFormat = og.DateFormat;
og.DateFormat = fmt;
try
{
//// converting to OracleDate
OracleDate odacDate = new OracleDate(date);
//// setting format for ToString()
OracleGlobalization.SetThreadInfo(og);
return odacDate.ToString();
}
catch (OracleTypeException ex)
{
if (ex.Number == 1820)
{
//// described issue
}
throw;
}
finally
{
og.DateFormat = prevFormat;
OracleGlobalization.SetThreadInfo(og);
}
}
static void Main(string[] args)
{
var x = OracleDateToChar(DateTime.Now, "mm-dd-yyyy");
var y = OracleDateToChar(DateTime.Now, "mm-dd-yyyy HH24:Mi:ss");
var z = OracleDateToChar(DateTime.Now, "IW"); //// exception
}
}
}
It works well with formats like "mm-dd-yyyy", "mm-dd-yyyy HH24:Mi:ss", but unfortunately it doesn't work with "output-only" formats like "IW" (output-only formats are formats that you can specify in TO*_DATETIME funcitons according to Table 9-4 on http://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_commands_1029.htm).
When I call for example
OracleDateToChar(DateTime.Now, "IW")
I get ORA-01820 format code cannot appear in date input format exception in ToString() line.
I'd understand if I got this error in ToDate() method, but in ToString() it seems to be a bug in ODP.NET.
Question: Is there a way to implement OracleDateToChar method that can handle output-only formats? (assuming that calling select to_char(:date, :fmt) from nvl; from oracle database is not an option)
The point about that Oracle documentation is that it applies to DATE_FORMAT which is part of the Oracle language. Therefore you can only execute it as a PL/SQL statement which is why you cannot get it to work client side: IW is not a valid format mask for ODP.Net globalization as far as I know. In fact the ODP globalization DateFormat defaults to whatever you have in NLS_DATE_FORMAT locally which is a full date format string, whereas IW is for getting the week of the year rather than for formatting a date itself. As far as I know, nothing in the .Net framework will recognise that Oracle-specific string, so in order for it to work you would need to issue a command to Oracle and get the result back, as per the example on that page:
CONSIDER mydatetime
DATE_FORMAT MON-RRRR-DD-HH24
That seems like a lot of overkill to change a date format. There are some good alternative siggestions which are client-side .Net in this SO answer
Further Reading
The Oracle docs for the Oracle Date Structure (OracleDate) ToString() method notes that
The returned value is a string representation of the OracleDate in the
format specified by the thread's OracleGlobalization.DateFormat
property
(My emphasis). The definition for this can be found here. A useful list of allowed format strings for NLS_DATE_FORMAT, and therefore by extension OracleDate.ToString, can be found here.
Background: We have a system that receives data from another backend system. We handle the displaying of that data, and we have our own XML templates to control how certain things are displayed (i.e. we have our own column templates to dictate what the column headers are, etc.) One thing we would like to support is the ability to provide a mask for these column templates that would apply to the values coming from the backend. Below is a scenario that I'm having trouble with.
Problem: I can't seem to get a simple string format working. I'd like to format a STRING value of four digits (i.e. "1444") in a time format (i.e. "14:44"). I've tried:
String.Format("{0:00:00}", "1444")
Note the importance of the input being a STRING. If I supply an int value, the format will work. The reason I cannot use this is because all the data we receive from the backend is in string format, and we'd like for this to be generic (so casting isn't really an option).
By generic, I mean I'd like to specify a mask in our own XML templates, something like:
<MyColumnTemplate Id="MyColumn" Mask="00:00" />
and to use that mask in a string format call for string values? If the mask fails, we could just simply return the original value (as the String.Format() method already does by default).
Edit: To help clarify, here is a simplified version of what I'd like to be able to do in code:
string inputValue = "1444";
string maskValueFromXml = "00:00";
string mask = "{0:" + maskValueFromXml + "}";
string myDesiredEndResult = String.Format(mask, inputValue);
The thing is you are working string to string,since you ask for time and phone number they are all numbers then try this trick(if we can call it that :)):
string result = string.Format("{0:00:00}", int.Parse("1444"));
For phone number:
string result = string.Format("{0:000-000-0000}", int.Parse("1234560789"));
You can even place your desired masks in a dictionary for example and do this:
Dictionary<string, string> masks = new Dictionary<string, string>();
masks.Add("Phone", "{0:000-000-0000}");
masks.Add("Time", "{0:00:00}");
string test = "1234560789";
string result = string.Format(masks["Phone"], int.Parse(test));
Try with DateTime.TryParseExact, e.g:
DateTime dateEntered;
string input = "1444";
if (DateTime.TryParseExact(input, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
{
MessageBox.Show(dateEntered.ToString());
}
else
{
MessageBox.Show("You need to enter valid 24hr time");
}
After that, you can use string.Format, predefined formats on MSDN.
I'm using Visual Web Ripper to extract name and prices on products on a website.
When i extract the price from a table it comes in a form like this:
Kr. 129,30
I need to extract the 129,30, then turn the comma to a dot (129.30).
Visual Web Ripper can use scripts to modify the extracted content. It can use standard Regex, C# and VB.NET.
In the Regex tab I have found that
(\d+.)?(\d+)(.\d+)?
gives me 129,30, but then I can't change the comma into a dot.
Therefor I have to use C#. It comes with this standard script:
using System;
using VisualWebRipper.Internal.SimpleHtmlParser;
using VisualWebRipper;
public class Script
{
//See help for a definition of WrContentTransformationArguments.
public static string TransformContent(WrContentTransformationArguments args)
{
try
{
//Place your transformation code here.
//This example just returns the input data
return args.Content;
}
catch(Exception exp)
{
//Place error handling here
args.WriteDebug("Custom script error: " + exp.Message);
return "Custom script error";
}
}
}
How do I modify it to extract the number then replace the comma with a dot?
This is obviously Krona, so we should use the Swedish culture info to translate it. First we start with the input:
var original = "Kr. 129,30";
Get the culture:
using System.Globalization;
var culture = CultureInfo.GetCultureInfo("sv-SE");
This culture expects the currency string to be kr (case insensitive) but we have Kr.. So let's update it:
var format = (NumberFormatInfo)culture.NumberFormat.Clone();
format.CurrencySymbol = "Kr.";
And now the culture aware parse:
var number = Decimal.Parse(original, NumberStyles.Currency, format);
Now number contains a decimal that has been parsed correctly.
String.Replace is an option ( text.Replace(",", ".")).
It would be better to properly parse number with correct CultureInfo and than reformat it back with InvariantCulture.