Date/Time Utility tool

using System;
using System.Collections;
using Microsoft.Win32;
namespace EQTG.General.BasicTypes
{
    /// <summary>
    /// Simple useful time based functions not supplied by the .NET framework or EQTG specific in usefulness
    /// </summary>
    public sealed class TimeUtils
    {
        private TimeUtils()
        {
        }

        /// <summary>
        /// Class diagnostics instance
        /// </summary>
        //private static ClassDiagnostics OurDiagnostics = new ClassDiagnostics();

        /// <summary>
        /// Constant defining the number of seconds in an hour
        /// </summary>
        public const System.Int32 SecondsPerHour = 60 * 60;

        /// <summary>
        /// Constant defining the number of seconds in a day
        /// </summary>
        public const System.Int32 SecondsPerDay = SecondsPerHour * 24;

        /// <summary>
        /// Constant defining the number of minutes in a day
        /// </summary>
        public const System.Int32 MinutesPerDay = 24 * 60;

        /// <summary>
        /// DateTime objects have a notional granuality of Ticks. 1 Tick = 100 nanoseconds. TicksPerSecond Ticks = 1 second
        /// </summary>
        public const long TicksPerSecond = 10000000L;

        /// <summary>
        /// Turn a datetime into a time int that is used for instance on the TIC
        /// </summary>
        /// <param name="dt">System.DateTime to be turned into integer</param>
        /// <returns>Int representing the time</returns>
        public static int TimeAsInteger( System.DateTime dt )
        {
            int timeAsInteger        =    dt.Hour * 10000000;
            timeAsInteger        +=    dt.Minute * 100000;
            timeAsInteger        +=    dt.Second * 1000;
            timeAsInteger        +=    dt.Millisecond % 1000;
            return timeAsInteger;
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime during the current day
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <returns></returns>
        public static DateTime TodayTimeFromInteger( int timeAsInteger )
        {
            return TimeFromIntegerAndBaseDate( timeAsInteger, DateTime.Now);
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime on 1 Jan 1900
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <returns></returns>
        public static DateTime YearDotTimeFromInteger( int timeAsInteger )
        {
            return TimeFromIntegerAndBaseDate( timeAsInteger, DateTime.MinValue);
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime in the same day as baseDate
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <param name="baseDate"></param>
        /// <returns></returns>
        public static DateTime TimeFromIntegerAndBaseDate( int timeAsInteger, DateTime baseDate )
        {
            int hour, minute, second, millisecond;
            timeAsInteger -= (hour = timeAsInteger / 10000000) * 10000000;
            timeAsInteger -= (minute = timeAsInteger / 100000) * 100000;
            timeAsInteger -= (second = timeAsInteger / 1000) * 1000;
            millisecond = timeAsInteger;
            DateTime dateTime = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, hour, minute, second, millisecond);
            return dateTime;
        }

        /// <summary>
        /// Turn a system date time into a rover8 date (useful for database queries etc)
        /// </summary>
        /// <param name="dt">System.DateTime to be converted</param>
        /// <returns>Int of form 20020330</returns>
        public static int  Rover8FromDateTime( System.DateTime dt )
        {
            return dt.Year*10000 + dt.Month * 100 + dt.Day;
        }

        /// <summary>
        /// Datetime year month and date from rover8 string
        /// </summary>
        /// <param name="s">Rover8 String</param>
        /// <param name="dt">DateTime to set</param>
        /// <returns>Whether conversion succeeded</returns>
        public static bool DateTimeFromRover8String( out DateTime dt, string s )
        {
            try
            {
                int rover8Number = int.Parse( s );
                int year        = ( rover8Number / 10000 );
                int month        = ( rover8Number / 100 ) % 100;
                int day            = rover8Number % 100;

                dt = new DateTime( year, month, day, 0,0,0 );
                return true;
            }
            catch ( Exception e)
            {
                dt = DateTime.MinValue;
                return false;
            }
        }

        /// <summary>
        /// Converts a datetime into a format suitable for embedding into a sybase SQL statement
        /// A datetime value of DateTime.MinValue will reuslt in "NULL" being returned
        /// </summary>
        /// <param name="inString">string</param>
        public static string ToDatabase(DateTime dateTime)
        {    
            if (dateTime == DateTime.MinValue)    // Interpretted as NULL
                return "NULL";
            else
                return String.Format("'{0:MMM dd yyyy HH:mm}'", dateTime);
            //if
        }
        
        /// <summary>
        /// Bump specified DateTime past a weekend.
        /// No timezone adjustments made - straight 24-hour chunks added.
        /// Doesn't do any timezone conversions
        /// </summary>
        /// <param name="dt">Date Time to bump</param>
        /// <returns>Bumped DateTime</returns>
        public static DateTime BumpPastWeekend( DateTime dt )
        {
            switch ( dt.DayOfWeek )
            {
                case DayOfWeek.Saturday:
                    MoveDateTimeForwardToNextDay(ref dt);
                    MoveDateTimeForwardToNextDay(ref dt);
                    break;
                case DayOfWeek.Sunday:
                    MoveDateTimeForwardToNextDay(ref dt);
                    break;
            }
            return dt;

        }

        /// <summary>
        /// Moves the passed DateTime back until we hit the previous day.
        /// Inputs and outputs are both local time. We have to be careful because in DST adjustment days,
        /// the day can be longer or shorter than 24 hours.  We assume that the adjustment will not be more than 2 hours, and
        /// that days are longer than 2 hours :)
        /// </summary>
        /// <param name="dt">time to move</param>
        public static void MoveDateTimeBackToPrevDay( ref DateTime dt )
        {
            int curDay = dt.Day;
            dt.AddHours(-22);
            while (dt.Day == curDay)
                dt = dt.AddHours(-1);
        }

        /// <summary>
        /// Moves the passed DateTime forward until we hit the next day.
        /// Inputs and outputs are both local time. We have to be careful because in DST adjustment days,
        /// the day can be longer or shorter than 24 hours.  We assume that the adjustment will not be more than 2 hours, and
        /// that days are longer than 2 hours :)
        /// </summary>
        /// <param name="dt">time to move</param>
        public static void MoveDateTimeForwardToNextDay( ref DateTime dt )
        {
            int curDay = dt.Day;
            dt.AddHours(22);
            while (dt.Day == curDay)
                dt = dt.AddHours(1);
        }

        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> (moves specified DateTime back) at which the local time in
        /// the specified time zone was the time specified.
        /// </summary>
        /// <remarks>
        /// Inputs and outputs are UTC.  Converts to local time, gets the previous
        /// occurrence of specified local hour and minute, returns as UTC
        /// </remarks>
        /// <param name="utcStart">Test time</param>
        /// <param name="timezone">Timezone of test time</param>
        /// <param name="hour">Hour of prev occurrence</param>
        /// <param name="minute">Minute of prev occurrence</param>
        /// <returns>Previous Weekday UTC DateTime to test date</returns>

        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> (moves specified DateTime back) at which the local
        /// time in the specified time zone will next be the time specified.
        /// </summary>
        /// <remarks>
        /// Inputs and outputs are UTC.  Converts to local time, gets the next occurrence of specified
        /// local hour and minute, returns as UTC
        /// </remarks>
        /// <param name="utcStart">Test time</param>
        /// <param name="timezone">Timezone of test time</param>
        /// <param name="hour">Hour of prev occurrence</param>
        /// <param name="minute">Minute of prev occurrence</param>
        /// <returns>Previous Weekday UTC DateTime to test date</returns>
        public static string XMLStringToDateString(string xmlString)
        {
            string result = "";
            try
            {
                DateTime date = DateTime.ParseExact(xmlString, "yyyy-MM-dd", new System.Globalization.DateTimeFormatInfo());
                result = String.Format("{0:dd MMM yyyy}", date);
            }
            catch (FormatException)
            {
            }

            return result;
        }

        public static DateTime Max(DateTime a, DateTime b)
        {
            return a > b ? a : b;
        }

        public static DateTime Min(DateTime a, DateTime b)
        {
            return a > b ? b : a;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解压密码 123456 尽供学习和演示, 不得用于商业活动, 请自觉在学习后删除。 Base Analyzer: - Modes: Real-time mode with data buffering (optional modes: recording and post-processing) - Channels: Single channel measurements (optional: dual channel measurements & analysis) - Views: Time Series, Spectrum and Phase (optional: 3-D Surface, Spectrogram) - Settings: up to 16 bit/48kHz, FFT sizes thru 32768 (optional: 24 bit/200kHz, FFT sizes to 1048576 pts) - Scaing: Linear, Log, Narrowband, 1/1 and 1/3 Octave (optional: up to 1/96 octave, Power Spectral Density) - Calibration: V, mV, dBV, dBmV, dBu, PA, psi, SPL, acceleration (optional: velocity or displacement) - Measurements: peak frequency and amplitude, total power, cursor measurements, right click action menus - Configuraton Files: quick test setup/recall for increased productivity - Printing, Annotation, Triggering, Markers and clipboard operations =============================================================================== Dual Channel Processing: adds dual channel operations - Real and Complex Transfer Functions, Coherence, Average, Cross Spectrum and cross channel delay compensation. Time domain measurements (Left, Right, L/R, L-R, R-L, L+R, X/Y, Y/X) and cross-channel delay compensation. Recording and Post Processing Modes: adds direct hard disk recording and playback. Post Processing mode provides comprehensive analysis from WAV files. Also adds precision digital filtering of wave files; includes Low Pass, High Pass, Bandpass, Notch and User Defined filter response. Includes flexible File Import/Export capabilities. Signal Generator Utility: adds single and multitone tone, pink or white noise, noise burst, frequency sweep, level sweep, pulse, saw, triangle, square, IMD test tones, DTMF, digital zero, and user defined WAV source. Can generate independent signals for left and right channels (requires dual channel option). Spectrogram View: displays the spectrum versus time for advanced joint time-frequency analysis. Magnitude represented by grey scale, full or custom color palette and selectable scroll direction (up/down, left/right). Ideal for detailed noise source identification, sound & vibration, voice analysis, sonogram and sound signature analysis. 3-D Surface View: displays the spectrum versus time in a 3-Dimensional perspective format. Includes solid or multicolor format. Provides an effective analysis tool for analyzing complex spectrum content over time. Distortion Analysis: adds on-the-fly real-time analysis for THD, THD+N, IMD, SNR, SINAD, and noise figure (NF) measurement utilities. Also adds a dedicated THD+N versus Frequency Utility that allows you to quickly and conveniently measure the distortion characteristics of your device over a range of frequencies. High Resolution Analysis: adds 24 bit sampling precision and sampling rates up to 200kHz (sound card dependent). Adds FFT sizes up to 1,048,576 points, and Octave scaling to 1/96. Advanced Scaling and Calibration: adds independent channel calibration and scaling for left and right channels with separate views for each. Useful for applications requiring separate channel scaling and calibration such as simultaneous sound and vibration measurements. This option also includes calibration conversions from Acceleration to Velocity or Displacement; also adds Power Specral Density scaling option for accurate noise measurements. Acoustic Toolset: adds the following tools and utilities: - Reverberation Time (RT60) utility features bar graph of reverberation time versus frequency band, 3-D Surface plot of the decay versus frequency and individual decay plots versus time. - Delay Finder measures delay between two channels in milliseconds, feet or meters. Speed of sound - converts the delay value between milliseconds, feet or meters. - Equivalent Noise (Leq) utility provides comprehensize noise level calculations for LeqT, Leq, Lpk , Lsel, Lmax, Lmin, L10, L50, L90. - Stereo Phase Scope for real-time monitoring and analysis of signal phase. Phase scope mode displays a standard oscilloscope X-Y orientation (lissajous pattern) for analysis of phase, polarity, missing channel detection and stereo separation monitoring. Automation Toolset: adds the following tools and utilities: - Macro Command Processor utility allows you to easily automate measurements, record SPL and spectral data at user specified intervals/duration with time/date stamp, save files with user-defined names using a script-based programming language. It uses the underlying DDE syntax for an automation solution without requiring a third party program. - Dynamic Data Exchange (DDE) allows the capability for an external program to control and read results from the analyzer in real time. Works with any program that supports DDE such as C++, VB, Excel, Access and others. - Data Logging utility produces an output text file containing selected spectral parameters + time-stamp for dynamic signal tracking and "unattended" event monitoring.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值