简体   繁体   中英

C# how convert hh:mm from excel cells

my value in excel cell has total time: 227:20 and this format [hh]:mm

but not convert in c# this format and show 11:20 in gridview

my code:

model.ezafekari = DateTime.FromOADate((double)ws.Cells[rowNum, 17].Value).ToString("HH:mm");

I'm assuming that your formula:

(double)ws.Cells[rowNum, 17].Value

Will yield what Excel will show as the General formatted value for the cell (in my experience, that's what you see for date/time cells). I'm not going to get code running against Excel.

Once you have that value, this should work:

var real = 9.472222222;         // should be (double)ws.Cells[rowNum, 17].Value
var days = (int)Math.Truncate(real);
var fracDays = real - days;
var fracHours = fracDays * 24.0;
var hours = (int) Math.Truncate(fracHours);
var minutes = (int) Math.Round ((fracHours - hours) * 60);
var totalHours = (days * 24) + hours;

var toShow = $"{totalHours}:{minutes}";

If you step through that code, you will see:

Variable Value
days 9
hours 11
minutes 20
totalHours 227
toShow 227:20

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