2015-11-06 62 views
1

我正在製作一個程序,這是一小段代碼,當您輸入日期時,我想要獲取星期編號。但是有一點小小的變化,我不想在運行該程序之後但在它之前提供參數。我想從RunCtrl + R開始我的程序。我的程序被稱爲getWeek。所以當我輸入Run getWeek 6-11-2015時,我應該得到一個TextBox,表示「第45周」。其純粹的愛好工作。以下是我的代碼查找週數。在啓動程序前輸入參數

public static int GetIso8601WeekOfYear(DateTime time) 
{ 
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); 
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) 
    { 
     time = time.AddDays(3); 
    } 
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); 
} 

問題是如何從Run中獲得DateTime time。請幫忙。

+0

它是一個控制檯應用程序? – hellogoodnight

+0

如果它是一個控制檯應用程序,當您調用它時可以提供參數。看到我的答案在這[問題](http://stackoverflow.com/questions/31816049/calling-stored-procedure-values-into-the-console-application-c-sharp/31816326#31816326)。 – Han

+0

這是一個表單應用程序。 –

回答

1

當你打電話給你的應用程序時,你可以提供一些參數。只需修改Program.cs中的Main方法即可。在Main方法中添加一個數組。然後,您可以運行該exe文件,並在exe後面添加一些值,例如WindowsApplication6 abc def ghi

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 

namespace WindowsFormsApplication6 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main(string[] args) 
     { 
      foreach (var arg in args) 
      { 
       MessageBox.Show(arg); 
      } 

      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 
} 

如果你想提供一些參數,從Visual Studio(就像當你正在調試),你可以在項目屬性添加。

enter image description here

+0

這是我一直在尋找。 @handodko謝謝 –

0

我覺得你的問題是,你不能你輸入string轉換爲DateTime。 這裏有一個方法,你可以用它來獲取DateTime

public static DateTime GetDateTimeFromString(string date) 
    { 
     string[] split = date.Split('-'); 
     int day = Convert.ToInt32(split[0]); 
     int month = Convert.ToInt32(split[1]); 
     int year = Convert.ToInt32(split[2]); 
     return new DateTime(year, month, day); 
    } 

注意:此功能是特定於您的格式化字符串。

然後,你可以調用這個方法是這樣的:

 string date = "06-11-2015"; 
     DateTime time = GetDateTimeFromString(date); 
     textBox1.Text = "Week " + Convert.ToString(GetIso8601WeekOfYear(time));