简体   繁体   中英

Extract time from String

I have this string which is a result of net time \\SERVER_NAME command in cmd :

Current time at \\SERVER_NAME is 3/31/2014 9:35:57 AM

The command completed successfully.

I want to extract the time displayed in this string (9:35:37 AM in this case). I think it is done using some regex. Can anyone help please?

Edit

I want absolutly to use regular expressions, This command is not ran against just one server.

Edit 2

I finally opted for the API presented in this documentation ( http://msdn.microsoft.com/en-us/library/aa370612(v=vs.85).aspx ), it is apprently a reliable one since it is using NTP.

Obtaining a remote time of day...

If you're trying to talk to machines with multiple cultures - and if the culture of the system on which you're running may vary as well - I would strongly advise that you avoid this text-based approach.

Instead, consider using the NetRemoteTOD function. There may be a managed version of this, but if not you can use P/Invoke to call it - see the relevant pinvoke.net entry . This will allow you to get the appropriate value without any text handling , making things much cleaner.

Original answer (may be useful to others)

Well I would use DateTime.Parse rather than a regular expression, after working out which part is the actual date/time. For example:

int startIndex = text.IndexOf(" is ") + 4;
DateTime dateTime = DateTime.Parse(text.Substring(startIndex));

That will get the value as a DateTime - you can then format just the time part however you want, eg

string time24 = dateTime.ToString("HH:mm:ss"); "09:35:37"
string time12 = dateTime.ToString("h:mm:ss tt"); "9:35:37 AM"

Note that this is very likely to be culture-sensitive; the code may well not work in other cultures. If you want to make this more reliable, I would stop using net time and instead use an API to talk to the server - I would really hope there'd be a way of doing this without using text handling...

If you really, really just want "whatever the part of the original string is after the date" then yes, you could use a regular expression - but I think it would be better to parse the value as a date/time to make sure it's genuinely the relevant data.

The simplest regex to only match the time would be something like:

\d\d?\:\d\d\:\d\d\s?(A|P)M

Is that what you're after?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM