Parse Date, Time and Date/Time Strings

Average rating
(1 vote)

Note: If you have only a time string, check out the Parse Time String snippet.

Function ParseDateStringAlpha(str)
	String str			// Format: ddmmmyyyy hh:mm:ss.xx
 
	Variable day, month, year, hour, minute, second, fraction
	String monthStr
 
	sscanf str, "%2d%3s%4d %d:%d:%d.%d", day, monthStr, year, hour, minute, second, fraction
 
	// For debugging only.
	// Print day, monthStr, year, hour, minute, second, fraction
 
	// This should be broken out into a subroutine for cleanliness.
	strswitch(monthStr)
		case "jan":
			month=1
			break
		case "feb":
			month=2
			break
		case "mar":
			month=3
			break
		case "apr":
			month=4
			break
		case "may":
			month=5
			break
		case "jun":
			month=6
			break
		case "jul":
			month=7
			break
		case "aug":
			month=8
			break
		case "sep":
			month=9
			break
		case "oct":
			month=10
			break
		case "nov":
			month=11
			break
		case "dec":
			month=12
			break
	endswitch
 
	Variable dt			// Igor date/time format.
	dt = date2secs(year, month, day)
	dt += 3600*hour + 60*minute + second + fraction
	return dt
End
 
//	ParseDateStringUSNumeric(str)
//	Returns seconds since 1/1/1904
Function ParseDateStringUSNumeric(str)
	String str			// Format: "mm/dd/yy hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" (preferred)
 
	Variable day, month, year, hour, minute, second
 
	// Do a trial run to determine if four digit year is used.
	Variable fourDigitYear
	sscanf str, "%2d/%2d/%d", month, day, year
	fourDigitYear = year > 99
 
	// sscanf requires Igor Pro 4 or later.
	if (fourDigitYear)
		sscanf str, "%2d/%2d/%4d %d:%d:%d", month, day, year, hour, minute, second
	else
		sscanf str, "%2d/%2d/%2d %d:%d:%d", month, day, year, hour, minute, second
		year += 2000			// Assume this century.
	endif
 
	// For debugging only.
	// Print month, day, year, hour, minute, second
 
	Variable dt			// Igor date/time format.
	dt = date2secs(year, month, day)
	dt += 3600*hour + 60*minute + second
	return dt
End
 
//	ParseTimeString(str)
//	Returns seconds. Time string format is assumed to be hh:mm or hh:mm:ss.
Function ParseTimeString(str)
	String str			// Format: "hh:mm" or "hh:mm:ss"
 
	Variable hour, minute, second
 
	// sscanf requires Igor Pro 4 or later.
	sscanf str, "%d:%d:%d", hour, minute, second
	if (V_flag == 2)
		second = 0
	endif
 
	// For debugging only.
	// Print hour, minute, second
 
	Variable dt			// Igor date/time format.
	dt = 3600*hour + 60*minute + second
	return dt
End

Back to top