Rectangle 27 1

Here is an argument for using <chrono>. This argument is not without its downsides. However I believe that in the long run, migrating towards this system will have benefits in type safety (correctness), performance and readability.

The downsides include the need for an 3rd party open source free header-only (one single header) library (for now):

This will also require C++11 or forward (naturally because it builds on <chrono>).

struct CCelC
#include <iomanip>
#include <iostream>

struct CCelC
{
    int year_;
    unsigned month_;
    unsigned day_;
    int hour_;
    int min_;
    int sec_;

    friend
    std::ostream&
    operator<<(std::ostream& os, const CCelC& x)
    {
        using namespace std;
        auto f = os.fill();
        os.fill('0');
        os << setw(4) << x.year_ << '-'
           << setw(2) << x.month_ << '-'
           << setw(2) << x.day_  << ' '
           << setw(2) << x.hour_ << ':'
           << setw(2) << x.min_ << ':'
           << setw(2) << x.sec_;
        os.fill(f);
        return os;
    }
};

And a test driver like this:

int
main()
{
    auto t = convert(90, 12*3600 + 52*60 + 31, 2015);
    std::cout << t << '\n';
}

The first stage builds a CCelC convert(int currentDay, float s, int y) conversion function that takes scalar inputs and output a CCelC which itself takes scalar inputs. The only use of <chrono> here is to input scalars, do the date computation, and output scalars:

This auxiliary (free, open-source one-header) library is needed to make the date computations convenient. It simply converts the input year/day/second field types into a std::chrono::time_point and then converts the std::chrono::time_point back out into year/month/day hour:minute:second scalars.

This solution is roughly equivalent to the currently accepted (and good) answer. Both solutions do not require calendrical arithmetic on the part of the user. This driver for this solution outputs:

2015-04-01 12:52:31

Imagine that the input code for convert decides to convert to <chrono>. This has significant type safety advantages. The compiler can now help you correctly convert units and protect you from confusing minutes with other integral types which have nothing to do with time units. This will effectively turn potential run-time errors into compile-time errors (catching your errors at compile-time is always better).

The convert function is now specified to take chrono types:

CCelC
convert(date::days currentDay, std::chrono::duration<float> s, date::year y)

date::days is just a type-alias for 24 std::chrono::hours. date::year is a new type, but helps disambiguate 2015 from some arbitrary integer. Now 2015_y has type year and the compiler propagates that information for you.

int
main()
{
    using namespace date;
    using namespace std::chrono_literals;
    auto t = convert(days{90}, 12h + 52min + 31s, 2015_y);
    std::cout << t << '\n';
}

There is a slight simplification in the implementation of convert with this new API:

There is no longer a need to convert the scalar input into the type-safe units of the <chrono> library. Much of the work of convert remains in adopting to the scalar format needs of CCelC.

But what if CCelC adopted <chrono>? Logically, if it did so, it should store a std::chrono::time_point instead of all of those fields. It is more space efficient, and it is easy (using date.h) to convert to field types when necessary. This might look like:

#include "date.h"
#include <chrono>
#include <iomanip>
#include <iostream>

struct CCelC
{
    using time_point = std::chrono::time_point<std::chrono::system_clock,
                                               std::chrono::seconds>;
    time_point tp_;

    friend
    std::ostream&
    operator<<(std::ostream& os, const CCelC& x)
    {
        using namespace date;
        return os << x.tp_;
    }
};

The functionality hasn't changed at all here. The output of this program is still 2015-04-01 12:52:31. And the sizeof requirements have just dramatically dropped. And the performance for arithmetic involving seconds, minutes, hours and days has just sky-rocketed.

The convert function has also just gained performance and simplification. Its input hasn't changed at all, so the driver is still the same. But now convert does not need to convert back to scalar types:

CCelC
convert(date::days currentDay, std::chrono::duration<float> s, date::year y)
{
    using namespace date;
    using namespace std::chrono;
    return {sys_days{y/jan/1} + currentDay + duration_cast<seconds>(s)};
}

The code now has been so significantly simplified that the chance for logic errors is greatly reduced. This simplification includes type-safety so that the compiler helps you catch logic errors. There are no more units conversions exposed in code, eliminating another class of errors. And if you wrap timers around this code, you will find it runs fast:

Maybe <chrono> isn't something you can completely adopt today. But there are advantages to adopting it in small stages, in small parts of your code. date.h can help. And down the road in 2 or 3 years, <chrono> is what you want to be aiming for. Eventually this is what the C++ community will be adopting universally. <ctime>/<time.h> is dead. The type-safety and performance advantages of <chrono> are too great. This answer is a description of how you can get on board with <chrono> gradually, one small piece of code at a time.

c++ - I'm having a hard time getting date/time components from day of ...

c++ date time epoch
Rectangle 27 0

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ASP.NET Prevent Previous Month Selection - Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Calendar ID="someCalendar" runat="server"
     OnVisibleMonthChanged="theVisibleMonthChanged" />
    </div>
    </form>
</body>
</html>




And the C# code for my demo is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Demo to show how one might prevent the user from selecting 
/// the previous month in ASP.NET
/// 
/// References: 
/// [1] - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.visiblemonthchanged.aspx
/// [2] - http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
/// </summary>
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // How to attach visibleMonthChanged event is explained in [1]
        someCalendar.VisibleMonthChanged +=
            new MonthChangedEventHandler(this.theVisibleMonthChanged);
    }

    protected void theVisibleMonthChanged(Object sender, MonthChangedEventArgs e) 
    {
        DateTime currentDate = DateTime.Now;
        DateTime dateOfMonthToDisable = currentDate.AddMonths(-1);
        if (e.NewDate.Month == dateOfMonthToDisable.Month)
        {
            someCalendar.VisibleDate = e.PreviousDate;
            // Custom date formats are explained in [2] 
            Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(), 
                "someScriptKey",
                "<script>" + 
                "alert(\"Can not go before today's month of " +
                currentDate.ToString("MMM-yyyy") +
                ".\");" + 
                "</script>"
            );
        }
    }
}

This solution alerts the visitor that clicking the next/previous link would show a disabled month, which is not the same as hiding one link or the other.

c# - Disable previous month link in Calendar control - Stack Overflow

c# .net .net-4.0 calendar web-controls
Rectangle 27 0

@echo off
SETLOCAL ENABLEEXTENSIONS

:: Here I recommend using the GetDateIntl function that works with international
:: date settings also (check end of file). Your method is OK but wont work
:: in all situations. You can use other ethods as well, like wmic.
call :GetDateIntl yearf month day 
echo/Using GetDateIntl you get: %yearf%-%month%-%day%
set "year2=%yearf:~-2%"

if "%month%"=="01" set mname=January
if "%month%"=="02" set mname=February
if "%month%"=="03" set mname=March
if "%month%"=="04" set mname=April
if "%month%"=="05" set mname=May
if "%month%"=="06" set mname=June
if "%month%"=="07" set mname=July
if "%month%"=="08" set mname=August
if "%month%"=="09" set mname=September
if "%month%"=="10" set mname=October
if "%month%"=="11" set mname=November
if "%month%"=="12" set mname=December

::Creates the folder structure based of the system date.
SET "datestr=%month%%day%%year2%"
SET "topdir=\\10.1.3.3\Information\Reports\Reports %yearf%\%month% %mname%\%day%"

::Outputs full File, this is the file that is used internally
SET "sourcedir=%topdir%"
SET "filename1=%sourcedir%\file%datestr%.txt"

:: Empty target file
echo/>"%topdir%\file%datestr%.csv"

:: You cannot use variables inside a FOR because each line is processed with the same
:: initial variable table, and changes only are applied after the FOR ends.
:: So if you create a variable, it will only be visible outside the FOR.
:: To fix this you have to use a function call, that runs every line with an 
:: updated variable table
FOR /f "usebackq tokens=1-3*" %%a IN ("%filename1%") DO call:PrintLine %%a %%b %%c

endlocal
goto:eof

:: This function is called for every line in the .txt file with the 3 columns 
:: as arguments
:PrintLine
  SET "_tmpdate=%3"

  :: CAREFUL: in your example, the date of the second line is missing the leading 0.
  :: If this really happenes in you .txt file then you need to check and correct this
  :: in your code. If all dates are ddmmyyyy format, this code is OK.
  SET "_tmpdate=%_tmpdate:~0,2%/%_tmpdate:~2,2%/%_tmpdate:~-4%" 
  :: Check if _tmpdates first char is "-". If it is, empty _tmpdate.
  IF "%_tmpdate:~0,1%"=="-" SET "_tmpdate="

  ECHO/%1,%2,%_tmpdate% >> "%topdir%\file%datestr%.csv"
goto:eof

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:GetDateIntl yy mm dd [/A]
:: Returns the current date on any machine with regional-independent settings
:: Arguments:
::   yy = variable name for the year output
::   mm = variable name for the month output
::   dd = variable name for the day output
::   /A = OPTIONAL, removes leading 0 on days/months smaller than 10 (example: 01 becomes 1)
:: Remarks:
::  Will return month in text format in regions with MMM month
::
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
  for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
    set '%%a'=%%i
    set '%%b'=%%j
    set '%%c'=%%k
  )
)
if /I "%'yy'%"=="" set "'yy'=%'aa'%"
if /I "%'yy'%"=="" ( set "'yy'=%'jj'%" & set "'dd'=%'tt'%" )
if %'yy'% LSS 100 set 'yy'=20%'yy'%
endlocal&set %1=%'yy'%&set %4 %2=%'mm'%&set %4 %3=%'dd'%&goto :EOF
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Not familiar with GetDateIntl. Why would I use that over just "DATE"? Googled it a little bit, says GetDate is for NT4/2k/XP, this function would not work on windows 7?

%Date% is region specific. This means if you use this script in a computer with date format different then yours, everything gets messed up. GetDateIntl works for systems with dates in any format. For example: If I run your original code in my PC it fails because my date format is DD/MM/YYYY. / GetDateIntl (my code) is not based on GetDate from google and also runs on win vista, 7, 8, 10, etc... If you are only going to run this on your PC, then you can use %DATE% without any problem.

Sorry to disappoint you: on my german windows, date gives me Geben Sie das neue Datum ein: (TT-MM-JJ), so your code fails because %'yy'% and %'dd'% are not defined. The longest list of methods to get a datestring independend of locale settings I found yet is npocmaka's answer to another question.

Good to know. Could you type echo %date% on a command prompt and tell me the result?

by the way - OP doesn't need any date processing, as he is just processing a textfile. That said, please see my link to npocmaka's list of reliable methods to get a date string or my personal favourite.

Script - Convert TXT File to CSV but format third column as date and r...

csv batch-file for-loop
Rectangle 27 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME,Encoding.Unicode);
            reader.ReadLine();
            XDocument doc = XDocument.Load(reader);

            foreach (XElement word in doc.Descendants("Word"))
            {
                DateTime date;
                Boolean isDate = DateTime.TryParse((string)word.Attribute("Text"), out date);
                if (isDate)
                {
                    word.Attribute("Text").SetValue(date.ToString("yyyy-MM-dd"));
                }

            }

        }
    }
}

This xml is in the database and not in the file. I need to do an update in SQL based

I you have a string then use StringReader(string) instead of StreamReader(filename);

sql - How to change the format of all dates in xml? - Stack Overflow

sql sql-server regex xml tsql
Rectangle 27 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    enum State
    {
        FIND_RECORD,
        GET_LOCATION,
        GET_DATES
    }
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            State state = State.FIND_RECORD;

            LocationDefinition location = null;
            string inputLine = "";
            while ((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                if (inputLine.Length == 0)
                {
                    state = State.FIND_RECORD;
                }
                else
                {
                    switch (state)
                    {
                        case State.FIND_RECORD :
                            if (inputLine.StartsWith("PlaceName"))
                            {
                                state = State.GET_LOCATION;
                            }
                            else
                            {
                                if (inputLine.StartsWith("Date"))
                                {
                                    state = State.GET_DATES;
                                }
                            }
                            break;
                        case State.GET_DATES :
                            if (location.dates == null) location.dates = new CountDefinition();
                            location.dates.dates.Add(new CountDefinition(inputLine));
                            break;
                        case State.GET_LOCATION :
                            location = new LocationDefinition(inputLine);
                            break;
                    }
                }
            }
        }
    }
    public class LocationDefinition
    {
        public static List<LocationDefinition> locations = new List<LocationDefinition>();
        public CountDefinition dates { get; set; }
        public string PlaceName { get; set; }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
        public double Elevation { get; set; }

        public LocationDefinition(string location)
        {
            string[] array = location.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            PlaceName = array[0];
            Longitude = double.Parse(array[1]);
            Latitude = double.Parse(array[2]);
            Elevation = double.Parse(array[3]);
            locations.Add(this);
         }
    }



    public class CountDefinition
    {
        public List<CountDefinition> dates = new List<CountDefinition>();
        public DateTime Date { get; set; }
        public int Count { get; set; }

        public CountDefinition() { ;}

        public CountDefinition(string count)
        {
            string[] array = count.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            Date = DateTime.Parse(array[0]);
            Count = int.Parse(array[1]);
            dates.Add(this);
        }
    }


}

Why would anybody use a 3rd party app to simply read a text file when it can easily be done with the string split function?

c# - CsvHelper - Read different record types in same CSV - Stack Overf...

c# csv csvhelper